javascript
SpringMVC+Mybatis基础知识和配置
SpringMVC和Mybatis簡單的記錄一下,因?yàn)楝F(xiàn)在有比較新的SpringBoot和Mybatis plus簡化了很多步驟。
SpringMVC
使用
- 創(chuàng)建maven項(xiàng)目,pom.xml
- 在 web.xml 中配置 DispatcherServlet
- springmvc.xml
- 創(chuàng)建 Handler
Spring MVC REST
REST:Representational State Transfer,資源表現(xiàn)層狀態(tài)轉(zhuǎn)換,是目前比較主流的一種互聯(lián)網(wǎng)軟件架構(gòu),它結(jié)構(gòu)清晰、標(biāo)準(zhǔn)規(guī)范、易于理解、便于擴(kuò)展。
- 資源(Resource)
網(wǎng)絡(luò)上的一個實(shí)體,或者說網(wǎng)絡(luò)中存在的一個具體信息,一段文本、一張圖片、一首歌曲、一段視頻等等,總之就是一個具體的存在。可以用一個 URI(統(tǒng)一資源定位符)指向它,每個資源都有對應(yīng)的一個特定的 URI,要獲取該資源時,只需要訪問對應(yīng)的 URI 即可。
- 表現(xiàn)層(Representation)
資源具體呈現(xiàn)出來的形式,比如文本可以用 txt 格式表示,也可以用 HTML、XML、JSON等格式來表示。
- 狀態(tài)轉(zhuǎn)換(State Transfer)
客戶端如果希望操作服務(wù)器中的某個資源,就需要通過某種方式讓服務(wù)端發(fā)生狀態(tài)轉(zhuǎn)換,而這種轉(zhuǎn)換是建立在表現(xiàn)層之上的,所有叫做"表現(xiàn)層狀態(tài)轉(zhuǎn)換"。
特點(diǎn)
- URL 更加簡潔。
- 有利于不同系統(tǒng)之間的資源共享,只需要遵守一定的規(guī)范,不需要進(jìn)行其他配置即可實(shí)現(xiàn)資源共享。
如何使用
REST 具體操作就是 HTTP 協(xié)議中四個表示操作方式的動詞分別對應(yīng) 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 對象關(guān)系映射
對象指?向?qū)ο?br /> 關(guān)系指關(guān)系型數(shù)據(jù)庫
Java 到 MySQL 的映射,開發(fā)者可以以?向?qū)ο蟮乃枷雭砉芾頂?shù)據(jù)庫。
如何使?
新建 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>新建數(shù)據(jù)表
use mybatis; create table t_account(id int primary key auto_increment,username varchar(11),password varchar(11),age int)
新建數(shù)據(jù)表對應(yīng)的實(shí)體類 Account
創(chuàng)建 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運(yùn)?環(huán)境 --><environments default="development"><environment id="development"><!-- 配置JDBC事務(wù)管理 --><transactionManager type="JDBC"></transactionManager><!-- POOLED配置JDBC數(shù)據(jù)源連接池 --><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 代理實(shí)現(xiàn)?定義接?
?定義接?,定義相關(guān)業(yè)務(wù)?法。
編寫與?法相對應(yīng)的 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、創(chuàng)建接?對應(yīng)的 Mapper.xml,定義接??法對應(yīng)的 SQL 語句。
statement 標(biāo)簽可根據(jù) SQL 執(zhí)?的業(yè)務(wù)選擇 insert、delete、update、select。
MyBatis 框架會根據(jù)規(guī)則?動創(chuàng)建接?實(shí)現(xiàn)類的代理對象。
規(guī)則:
Mapper.xml 中 namespace 為接?的全類名。
Mapper.xml 中 statement 的 id 為接?中對應(yīng)的?法名。
Mapper.xml 中 statement 的 parameterType 和接?中對應(yīng)?法的參數(shù)類型?致。
Mapper.xml 中 statement 的 resultType 和接?中對應(yīng)?法的返回值類型?致。
3、在 config.xml 中注冊 AccountRepository.xml
<!-- 注冊AccountMapper.xml --><mappers><mapper resource="mybatis/mapper/AccountMapper.xml"></mapper><mapper resource="mybatis/repository/AccountRepository.xml"></mapper></mappers>4、調(diào)?接?的代理對象完成相關(guān)的業(yè)務(wù)操作
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();//獲取實(shí)現(xiàn)接?的代理對象AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);//添加對象 // Account account = new Account(3L,"王五","111111",24); // int result = accountRepository.save(account); // sqlSession.commit();//查詢?nèi)繉ο?/span> // 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 框架需要:實(shí)體類、?定義 Mapper 接?、Mapper.xml
傳統(tǒng)的開發(fā)中上述的三個組件需要開發(fā)者?動創(chuàng)建,逆向?程可以幫助開發(fā)者來?動創(chuàng)建三個組件,減
輕開發(fā)者的?作量,提??作效率。
如何使?
MyBatis Generator,簡稱 MBG,是?個專?為 MyBatis 框架開發(fā)者定制的代碼?成器,可?動?成
MyBatis 框架所需的實(shí)體類、Mapper 接?、Mapper.xml,?持基本的 CRUD 操作,但是?些相對復(fù)
雜的 SQL 需要開發(fā)者??來完成。
新建 Maven ?程,pom.xml
創(chuàng)建 MBG 配置?件 generatorConfig.xml
1、jdbcConnection 配置數(shù)據(jù)庫連接信息。
2、javaModelGenerator 配置 JavaBean 的?成策略。
3、sqlMapGenerator 配置 SQL 映射?件?成策略。
4、javaClientGenerator 配置 Mapper 接?的?成策略。
5、table 配置?標(biāo)數(shù)據(jù)表(tableName:表名,domainObjectName:JavaBean 類名)。
創(chuàng)建 Generator 執(zhí)?類。
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();}} }總結(jié)
以上是生活随笔為你收集整理的SpringMVC+Mybatis基础知识和配置的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring基础知识和配置
- 下一篇: gradle idea java ssm