Mybatis动态代理模式实现CRUD
生活随笔
收集整理的這篇文章主要介紹了
Mybatis动态代理模式实现CRUD
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
項(xiàng)目實(shí)現(xiàn)的功能
查詢(xún)所有用戶信息
通過(guò)Id查詢(xún)用戶信息
添加用戶(回顯主鍵)
修改用戶信息
刪除用戶信息
通過(guò)用戶名字模糊查詢(xún)
一、引入依賴(lài)和工程結(jié)構(gòu)
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.william</groupId><artifactId>MybatisMapper</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency></dependencies></project>二、創(chuàng)建實(shí)體類(lèi)
User
package com.william.domain;import java.util.Date;/*** @author :lijunxuan* @date :Created in 2019/7/9 19:28* @description :* @version: 1.0*/ public class User {private Integer id;private String username;private String password;private String sex;private Date birthday;@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", password='" + password + '\'' +", sex='" + sex + '\'' +", birthday=" + birthday +'}';}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}}三、映射文件
1.UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.william.dao.UserMapper"><!--查詢(xún)所有用戶信息--><select id="findAll" resultType="com.william.domain.User">select * from user</select><!--通過(guò)ID查詢(xún)用戶信息--><select id="findById" parameterType="java.lang.Integer" resultType="com.william.domain.User">select * from user where id=#{id}</select><!--模糊查詢(xún)--><select id="findByUsername" parameterType="java.lang.String" resultType="com.william.domain.User">select * from user where username like "%"#{value}"%"</select><!--增加用戶信息 主鍵回顯--><insert id="insert" parameterType="com.william.domain.User"> -- selectKey: 查詢(xún)主鍵值 -- resultType: 主鍵類(lèi)型 -- keyColumn: 指定主鍵的列名 -- keyProperty: 主鍵對(duì)應(yīng)的屬性名 -- order:可選值:after ,before -- AFTER: 在執(zhí)行sql語(yǔ)句之后執(zhí)行查找主鍵操作 -- BEFORE: 在執(zhí)行sql語(yǔ)句之前執(zhí)行查找主鍵操作<selectKey resultType="java.lang.Integer" keyColumn="id" keyProperty="id" order="AFTER" >select last_insert_id()</selectKey>insert into user values (null ,#{username},#{password},#{sex},#{birthday})</insert><!--更新用戶信息--><update id="update" parameterType="com.william.domain.User">update user set username=#{username},password=#{password},sex=#{sex},birthday=#{birthday} where id=#{id}</update><!--刪除用戶信息--><delete id="delete" parameterType="java.lang.Integer">delete from user where id =#{id}</delete> </mapper>四、引入log4j
log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=debug, CONSOLE, LOGFILE, info# Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE# CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n# LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n五、測(cè)試類(lèi)
TestCrud
package com.william;import com.william.dao.UserMapper; import com.william.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test;import javax.annotation.Resource; import java.io.IOException; import java.io.InputStream; import java.util.List;/*** @author :lijunxuan* @date :Created in 2019/7/12 10:16* @description :* @version: 1.0*/ public class TestCrud {/*** 查詢(xún)所有用戶信息* @throws IOException*/@Testpublic void findAll() throws IOException {InputStream inputStream = Resources.getResourceAsStream("Mybatis-configuration.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();//獲取某接口的動(dòng)態(tài)代理對(duì)象(獲取某接口的一個(gè)實(shí)現(xiàn)類(lèi))UserMapper userMapper = sqlSession.getMapper(UserMapper.class);List<User> userList = userMapper.findAll();for (User user : userList) {System.out.println(user);}sqlSession.close();}/****通過(guò)Id查詢(xún)用戶信息* @throws IOException*/@Testpublic void findById() throws IOException {InputStream inputStream = Resources.getResourceAsStream("Mybatis-configuration.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();//獲取某接口的動(dòng)態(tài)代理對(duì)象(獲取某接口的一個(gè)實(shí)現(xiàn)類(lèi))UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User findByIdUser = userMapper.findById(43);System.out.println(findByIdUser);sqlSession.close();}/*** 模糊查詢(xún)* 通過(guò)用戶名模糊查詢(xún)* @throws IOException*/@Testpublic void findByUsername() throws IOException {InputStream inputStream = Resources.getResourceAsStream("Mybatis-configuration.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();//獲取某接口的動(dòng)態(tài)代理對(duì)象(獲取某接口的一個(gè)實(shí)現(xiàn)類(lèi))UserMapper userMapper = sqlSession.getMapper(UserMapper.class);List<User> findByIdUsernameList = userMapper.findByUsername("a");for (User user : findByIdUsernameList) {System.out.println(user);}sqlSession.close();}/*** 增加用戶信息* @throws IOException*/@Testpublic void insert() throws IOException {InputStream inputStream = Resources.getResourceAsStream("Mybatis-configuration.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();//獲取某接口的動(dòng)態(tài)代理對(duì)象(獲取某接口的一個(gè)實(shí)現(xiàn)類(lèi))UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User user= new User();user.setUsername("today");user.setPassword("hello");user.setSex("女");userMapper. insert(user);//事務(wù)提交sqlSession.commit();System.out.println("添加后用戶的id為:"+user.getId());sqlSession.close();}/*** 更新用戶信息* @throws IOException*/@Testpublic void update() throws IOException {InputStream inputStream = Resources.getResourceAsStream("Mybatis-configuration.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();//獲取某接口的動(dòng)態(tài)代理對(duì)象(獲取某接口的一個(gè)實(shí)現(xiàn)類(lèi))UserMapper userMapper = sqlSession.getMapper(UserMapper.class);User user= new User();user.setId(45);user.setUsername("today");user.setPassword("hello");user.setSex("女");userMapper. update(user);//事務(wù)提交sqlSession.commit();sqlSession.close();}/*** 通過(guò)id刪除用戶信息* @throws IOException*/@Testpublic void delete() throws IOException {InputStream inputStream = Resources.getResourceAsStream("Mybatis-configuration.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();//獲取某接口的動(dòng)態(tài)代理對(duì)象(獲取某接口的一個(gè)實(shí)現(xiàn)類(lèi))UserMapper userMapper = sqlSession.getMapper(UserMapper.class);userMapper. delete(50);//事務(wù)提交sqlSession.commit();sqlSession.close();} }【重點(diǎn)】mybatis動(dòng)態(tài)代理模式開(kāi)發(fā)的要求
1.dao接口和映射文件必須路徑相同,文件名相同(dao接口和映射文件必須在同一個(gè)文件夾中,文件名必須相同)
如圖所示:
2.namespace必須是 接口的全限定類(lèi)名
3.映射文件中的id值必須是接口的方法名
4.參數(shù)類(lèi)型和返回值類(lèi)也必須是匹配的
總結(jié)
以上是生活随笔為你收集整理的Mybatis动态代理模式实现CRUD的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 心累了沉默了微信网名128个
- 下一篇: 惩恶扬善打云南一个地名