javascript
SpringMVC+Mybatis基础知识和配置
SpringMVC和Mybatis簡單的記錄一下,因為現在有比較新的SpringBoot和Mybatis plus簡化了很多步驟。
SpringMVC
使用
- 創建maven項目,pom.xml
- 在 web.xml 中配置 DispatcherServlet
- springmvc.xml
- 創建 Handler
Spring MVC REST
REST:Representational State Transfer,資源表現層狀態轉換,是目前比較主流的一種互聯網軟件架構,它結構清晰、標準規范、易于理解、便于擴展。
- 資源(Resource)
網絡上的一個實體,或者說網絡中存在的一個具體信息,一段文本、一張圖片、一首歌曲、一段視頻等等,總之就是一個具體的存在。可以用一個 URI(統一資源定位符)指向它,每個資源都有對應的一個特定的 URI,要獲取該資源時,只需要訪問對應的 URI 即可。
- 表現層(Representation)
資源具體呈現出來的形式,比如文本可以用 txt 格式表示,也可以用 HTML、XML、JSON等格式來表示。
- 狀態轉換(State Transfer)
客戶端如果希望操作服務器中的某個資源,就需要通過某種方式讓服務端發生狀態轉換,而這種轉換是建立在表現層之上的,所有叫做"表現層狀態轉換"。
特點
- URL 更加簡潔。
- 有利于不同系統之間的資源共享,只需要遵守一定的規范,不需要進行其他配置即可實現資源共享。
如何使用
REST 具體操作就是 HTTP 協議中四個表示操作方式的動詞分別對應 CRUD 基本操作。
GET 用來表示獲取資源。
POST 用來表示新建資源。
PUT 用來表示修改資源。
DELETE 用來表示刪除資源。
Handler`
import entity.Student; import entity.User; import repository.StudentRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.web.bind.annotation.*;import javax.servlet.http.HttpServletResponse; import java.util.Collection;@RestController @RequestMapping("/rest") public class RESTHandeler {@Autowiredprivate StudentRepository studentRepository;@GetMapping("/findAll")public Collection<Student> findAll(HttpServletResponse response){response.setContentType("text/json;charset=UTF-8");return studentRepository.findAll();}@GetMapping("/findById/{id}")public Student findById(@PathVariable("id") long id){return studentRepository.findById(id);}@PostMapping("/save")public void save(@RequestBody Student student){studentRepository.saveOrUpdate(student);}@PutMapping("/update")public void update(@RequestBody Student student){studentRepository.saveOrUpdate(student);}@DeleteMapping("/deleteById/{id}")public void deleteById(@PathVariable("id") long id){studentRepository.deleteById(id);}}StudentRepository
package repository;import entity.Student;import java.util.Collection;public interface StudentRepository {public Collection<Student> findAll();public Student findById(long id);public void saveOrUpdate(Student student);public void deleteById(long id); }StudentRepositoryImpl
import entity.Student; import repository.StudentRepository; import org.springframework.stereotype.Repository;import java.util.Collection; import java.util.HashMap; import java.util.Map;@Repository public class StudentRepositoryImpl implements StudentRepository {private static Map<Long,Student> studentMap;static{studentMap = new HashMap<>();studentMap.put(1L,new Student(1L,"張三",22));studentMap.put(2L,new Student(2L,"李四",23));studentMap.put(3L,new Student(3L,"王五",24));}@Overridepublic Collection<Student> findAll() {return studentMap.values();}@Overridepublic Student findById(long id) {return studentMap.get(id);}@Overridepublic void saveOrUpdate(Student student) {studentMap.put(student.getId(),student);}@Overridepublic void deleteById(long id) {studentMap.remove(id);} }Mybatis
MyBatis
ORMapping: Object Relationship Mapping 對象關系映射
對象指?向對象
關系指關系型數據庫
Java 到 MySQL 的映射,開發者可以以?向對象的思想來管理數據庫。
如何使?
新建 Maven ?程,pom.xml
<dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.6</version><scope>provided</scope></dependency> </dependencies> <build><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource></resources> </build>新建數據表
use mybatis; create table t_account(id int primary key auto_increment,username varchar(11),password varchar(11),age int)
新建數據表對應的實體類 Account
創建 MyBatis 的配置?件 config.xml,?件名可?定義
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration><!-- 配置MyBatis運?環境 --><environments default="development"><environment id="development"><!-- 配置JDBC事務管理 --><transactionManager type="JDBC"></transactionManager><!-- POOLED配置JDBC數據源連接池 --><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"> </property><property name="url" value="jdbc:mysql://localhost:3306/mybatis? useUnicode=true&characterEncoding=UTF-8"></property><property name="username" value="root"></property><property name="password" value="root"></property></dataSource></environment></environments> </configuration>通過 Mapper 代理實現?定義接?
?定義接?,定義相關業務?法。
編寫與?法相對應的 Mapper.xml。
1、?定義接?
package repository; import entity.Account; import java.util.List; public interface AccountRepository {public int save(Account account);public int update(Account account);public int deleteById(long id);public List<Account> findAll();public Account findById(long id); }2、創建接?對應的 Mapper.xml,定義接??法對應的 SQL 語句。
statement 標簽可根據 SQL 執?的業務選擇 insert、delete、update、select。
MyBatis 框架會根據規則?動創建接?實現類的代理對象。
規則:
Mapper.xml 中 namespace 為接?的全類名。
Mapper.xml 中 statement 的 id 為接?中對應的?法名。
Mapper.xml 中 statement 的 parameterType 和接?中對應?法的參數類型?致。
Mapper.xml 中 statement 的 resultType 和接?中對應?法的返回值類型?致。
3、在 config.xml 中注冊 AccountRepository.xml
<!-- 注冊AccountMapper.xml --><mappers><mapper resource="mybatis/mapper/AccountMapper.xml"></mapper><mapper resource="mybatis/repository/AccountRepository.xml"></mapper></mappers>4、調?接?的代理對象完成相關的業務操作
package mybatis.test;import mybatis.entity.Account; import mybatis.repository.AccountRepository; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.InputStream; import java.util.List;public class Test2 {public static void main(String[] args) {InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();//獲取實現接?的代理對象AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);//添加對象 // Account account = new Account(3L,"王五","111111",24); // int result = accountRepository.save(account); // sqlSession.commit();//查詢全部對象 // List<Account> list = accountRepository.findAll(); // for (Account account:list){ // System.out.println(account); // } // sqlSession.close();//通過id查詢對象 // Account account = accountRepository.findById(3L); // System.out.println(account); // sqlSession.close();//修改對象 // Account account = accountRepository.findById(3L); // account.setUsername("?明"); // account.setPassword("000"); // account.setAge(18); // int result = accountRepository.update(account); // sqlSession.commit(); // System.out.println(result); // sqlSession.close();//通過id刪除對象int result = accountRepository.deleteById(3L);System.out.println(result);sqlSession.commit();sqlSession.close();} }逆向?程
MyBatis 框架需要:實體類、?定義 Mapper 接?、Mapper.xml
傳統的開發中上述的三個組件需要開發者?動創建,逆向?程可以幫助開發者來?動創建三個組件,減
輕開發者的?作量,提??作效率。
如何使?
MyBatis Generator,簡稱 MBG,是?個專?為 MyBatis 框架開發者定制的代碼?成器,可?動?成
MyBatis 框架所需的實體類、Mapper 接?、Mapper.xml,?持基本的 CRUD 操作,但是?些相對復
雜的 SQL 需要開發者??來完成。
新建 Maven ?程,pom.xml
創建 MBG 配置?件 generatorConfig.xml
1、jdbcConnection 配置數據庫連接信息。
2、javaModelGenerator 配置 JavaBean 的?成策略。
3、sqlMapGenerator 配置 SQL 映射?件?成策略。
4、javaClientGenerator 配置 Mapper 接?的?成策略。
5、table 配置?標數據表(tableName:表名,domainObjectName:JavaBean 類名)。
創建 Generator 執?類。
package nixiang.test;import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.exception.InvalidConfigurationException; import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.internal.DefaultShellCallback; import sun.applet.Main;import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List;public class main {public static void main(String[] args) {List<String> warings = new ArrayList<String>();boolean overwrite = true;String genCig = "/generatorConfig.xml";File configFile = new File(Main.class.getResource(genCig).getFile());ConfigurationParser configurationParser = newConfigurationParser(warings);Configuration configuration = null;try {configuration = configurationParser.parseConfiguration(configFile);} catch (IOException e) {e.printStackTrace();} catch (XMLParserException e) {e.printStackTrace();}DefaultShellCallback callback = new DefaultShellCallback(overwrite);MyBatisGenerator myBatisGenerator = null;try {myBatisGenerator = newMyBatisGenerator(configuration,callback,warings);} catch (InvalidConfigurationException e) {e.printStackTrace();}try {myBatisGenerator.generate(null);} catch (SQLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}} }總結
以上是生活随笔為你收集整理的SpringMVC+Mybatis基础知识和配置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring基础知识和配置
- 下一篇: Linux虚拟机或阿里云部署本地Java