mybatis框架:共四天
明确:我们在实际开发中,都是越简便越好,所以都是采用不写dao实现类的方式。
不管使用XML还是注解配置。第二天:mybatis基本使用
mybatis的单表crud操作
mybatis的参数和返回值
mybatis的dao编写
mybatis配置的细节
几个标签的使用
持久层总图
Mybatis第二天讲义: 第3章 Mybatis 的参数深入
3.2 传递 pojo 包装对象
开发中通过 pojo 传递查询条件 ,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。
Pojo 类中包含 pojo
需求:根据用户名查询用户信息,查询条件放到 QueryVo 的 user 属性中。select * from user where username like #{user.username};
05.使用Mybatis完成CRUD
创建数据库: eesy_mybatis
导入SQL脚本文件: mybatisdb.sql
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL auto_increment, `username` varchar(32) NOT NULL COMMENT '用户名称', `birthday` datetime default NULL COMMENT '生日', `sex` char(1) default NULL COMMENT '性别', `address` varchar(256) default NULL COMMENT '地址', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (41,'老王','2018-02-27 17:47:08','男','北京'),(42,'小二王','2018-03-02 15:09:37','女','北京金燕龙'),(43,'小二王','2018-03-04 11:34:34','女','北京金燕龙'),(45,'传智播客','2018-03-04 12:04:06','男','北京金燕龙'),(46,'老王','2018-03-07 17:37:26','男','北京'),(48,'小马宝莉','2018-03-08 11:44:00','女','北京修正');
DROP TABLE IF EXISTS `account`; CREATE TABLE `account` ( `ID` int(11) NOT NULL COMMENT '编号', `UID` int(11) default NULL COMMENT '用户编号', `MONEY` double default NULL COMMENT '金额', PRIMARY KEY (`ID`), KEY `FK_Reference_8` (`UID`), CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `account`(`ID`,`UID`,`MONEY`) values (1,41,1000),(2,45,1000),(3,41,2000);
DROP TABLE IF EXISTS `role`; CREATE TABLE `role` ( `ID` int(11) NOT NULL COMMENT '编号', `ROLE_NAME` varchar(30) default NULL COMMENT '角色名称', `ROLE_DESC` varchar(60) default NULL COMMENT '角色描述', PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `role`(`ID`,`ROLE_NAME`,`ROLE_DESC`) values (1,'院长','管理整个学院'),(2,'总裁','管理整个公司'),(3,'校长','管理整个学校'); DROP TABLE IF EXISTS `user_role`; CREATE TABLE `user_role` ( `UID` int(11) NOT NULL COMMENT '用户编号', `RID` int(11) NOT NULL COMMENT '角色编号', PRIMARY KEY (`UID`,`RID`), KEY `FK_Reference_10` (`RID`), CONSTRAINT `FK_Reference_10` FOREIGN KEY (`RID`) REFERENCES `role` (`ID`), CONSTRAINT `FK_Reference_9` FOREIGN KEY (`UID`) REFERENCES `user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user_role`(`UID`,`RID`) values (41,1),(45,1),(41,2);
代码:
day02_eesy_01mybatisCRUD
1 回顾Mybatis的环境搭建-实现查询所有功能
pom.xml
<groupId>com.itheima</groupId> <artifactId>day02_eesy_01mybatisCRUD</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> </dependencies>
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 # 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=c:\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
实体类
com.itheima.domain
User
package com.itheima.domain; import java.io.Serializable; import java.util.Date; /** * @author 黑马程序员 * @Company http:// */ public class User implements Serializable { private Integer userId; private String userName; private String userAddress; private String userSex; private Date userBirthday; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } public Date getUserBirthday() { return userBirthday; } public void setUserBirthday(Date userBirthday) { this.userBirthday = userBirthday; } @Override public String toString() { return "User{" + "userId=" + userId + ", userName='" + userName + '\'' + ", userAddress='" + userAddress + '\'' + ", userSex='" + userSex + '\'' + ", userBirthday=" + userBirthday + '}'; } }
com.itheima.domain
QueryVo
package com.itheima.domain; /** * @author 黑马程序员 * @Company http:// */ public class QueryVo { private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
持久层接口文件
IUserDao
package com.itheima.dao; import com.itheima.domain.QueryVo; import com.itheima.domain.User; import java.util.List; /** * @author 黑马程序员 * @Company http:// * * 用户的持久层接口 */ public interface IUserDao { /** * 查询所有用户 * @return */ List<User> findAll(); /** * 保存用户 * @param user */ void saveUser(User user); /** * 更新用户 * @param user */ void updateUser(User user); /** * 根据Id删除用户 * @param userId */ void deleteUser(Integer userId); /** * 根据id查询用户信息 * @param userId * @return */ User findById(Integer userId); /** * 根据名称模糊查询用户信息 * @param username * @return */ List<User> findByName(String username); /** * 查询总用户数 * @return */ int findTotal(); /** * 根据queryVo中的条件查询用户 * @param vo * @return */ List<User> findUserByVo(QueryVo vo); }
映射Mapper.xml配置文件
IUserDaoMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.itheima.dao.IUserDaoMapper"> <!-- 配置 查询结果的列名和实体类的属性名的对应关系 --> <resultMap id="userMap" type="uSeR"> <!-- 主键字段的对应 --> <id property="userId" column="id"></id> <!--非主键字段的对应--> <result property="userName" column="username"></result> <result property="userAddress" column="address"></result> <result property="userSex" column="sex"></result> <result property="userBirthday" column="birthday"></result> </resultMap> <!-- 查询所有 --> <select id="findAll" resultMap="userMap"> <!--select id as userId,username as userName,address as userAddress,sex as userSex,birthday as userBirthday from user;--> select * from user; </select> <!-- 保存用户 --> <insert id="saveUser" parameterType="user"> <!-- 配置插入操作后,获取插入数据的id --> <selectKey keyProperty="userId" keyColumn="id" resultType="int" order="AFTER"> select last_insert_id(); </selectKey> insert into user(username,address,sex,birthday)values(#{userName},#{userAddress},#{userSex},#{userBirthday}); </insert> <!-- 更新用户 --> <update id="updateUser" parameterType="USER"> update user set username=#{userName},address=#{userAddress},sex=#{userAex},birthday=#{userBirthday} where id=#{userId} </update> <!-- 删除用户--> <delete id="deleteUser" parameterType="java.lang.Integer"> <!-- dao层接口中的deleteUser方法的参数有且仅只有一个时,可以用任意的占位符--> delete from user where id = #{uid} </delete> <!-- 根据id查询用户 --> <select id="findById" parameterType="INT" resultMap="userMap"> select * from user where id = #{uid} </select> <!-- 根据名称模糊查询 --> <select id="findByName" parameterType="string" resultMap="userMap"> select * from user where username like #{name} <!-- select * from user where username like '%${value}%'--> </select> <!-- 获取用户的总记录条数 --> <select id="findTotal" resultType="int"> select count(id) from user; </select> <!-- 根据queryVo的条件查询用户 --> <select id="findUserByVo" parameterType="com.itheima.domain.QueryVo" resultMap="userMap"> select * from user where username like #{user.username} </select> </mapper>
jdbcConfig.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/eesy_mybatis ?serverTimezone=Asia/Shanghai jdbc.username=root jdbc.password=root
SqlMapConfig.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> <!-- 配置properties 可以在标签内部配置连接数据库的信息。也可以通过属性引用外部配置文件信息 resource属性: 常用的 用于指定配置文件的位置,是按照类路径的写法来写,并且必须存在于类路径下。 url属性: 是要求按照Url的写法来写地址 URL:Uniform Resource Locator 统一资源定位符。它是可以唯一标识一个资源的位置。 它的写法: http://localhost:8080/mybatisserver/demo1Servlet 协议 主机 端口 URI URI:Uniform Resource Identifier 统一资源标识符。它是在应用中可以唯一定位一个资源的。 --> <properties url="file:///D:/IdeaProjects/day02_eesy_01mybatisCRUD/src/main/resources/jdbcConfig.properties"> <!-- <property name="driver" value="com.mysql.cj.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis ?serverTimezone=Asia/Shanghai"></property> <property name="username" value="root"></property> <property name="password" value="root"></property>--> </properties> <!--使用typeAliases配置别名,它只能配置domain中类的别名 --> <typeAliases> <!--typeAlias用于配置别名。type属性指定的是实体类全限定类名。alias属性指定别名,当指定了别名就再区分大小写 <typeAlias type="com.itheima.domain.User" alias="user"></typeAlias>--> <!-- 用于指定要配置别名的包,当指定之后,该包下的实体类都会注册别名,并且类名就是别名,不再区分大小写--> <package name="com.itheima.domain"></package> </typeAliases> <!--配置环境--> <environments default="mysql"> <!-- 配置mysql的环境--> <environment id="mysql"> <!-- 配置事务 --> <transactionManager type="JDBC"></transactionManager> <!--配置连接池--> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </dataSource> </environment> </environments> <!-- 配置映射文件的位置 --> <mappers> <!--<mapper resource="com/itheima/dao/IUserDao.xml"></mapper>--> <!-- package标签是用于指定dao接口所在的包,当指定了之后就不需要在写mapper以及resource或者class了 --> <package name="com.itheima.dao"></package> </mappers> </configuration>
测试类
MybatisTest
package com.itheima.test; import com.itheima.dao.IUserDao; import com.itheima.domain.QueryVo; import com.itheima.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.After; import org.junit.Before; import org.junit.Test; import java.io.InputStream; import java.util.Date; import java.util.List; /** * @author 黑马程序员 * @Company http://www.ithiema.com * * 测试mybatis的crud操作 */ public class MybatisTest { private InputStream in; private SqlSession sqlSession; private IUserDao userDao; @Before//用于在测试方法执行之前执行 public void init()throws Exception{ //1.读取配置文件,生成字节输入流 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.获取SqlSessionFactory SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //3.获取SqlSession对象 sqlSession = factory.openSession(); //4.获取dao的代理对象 userDao = sqlSession.getMapper(IUserDao.class); } @After//用于在测试方法执行之后执行 public void destroy()throws Exception{ //提交事务 sqlSession.commit(); //6.释放资源 sqlSession.close(); in.close(); } /** * 测试查询所有 */ @Test public void testFindAll(){ //5.执行查询所有方法 List<User> users = userDao.findAll(); for(User user : users){ System.out.println(user); } } /** * 测试保存操作 */ @Test public void testSave(){ User user = new User(); user.setUserName("modify User property"); user.setUserAddress("北京市顺义区"); user.setUserSex("男"); user.setUserBirthday(new Date()); System.out.println("保存操作之前:"+user); //5.执行保存方法 userDao.saveUser(user); System.out.println("保存操作之后:"+user); } /** * 测试更新操作 */ @Test public void testUpdate(){ User user = new User(); user.setUserId(50); user.setUserName("mybastis update user"); user.setUserAddress("北京市顺义区"); user.setUserSex("女"); user.setUserBirthday(new Date()); //5.执行保存方法 userDao.updateUser(user); } /** * 测试删除操作 */ @Test public void testDelete(){ //5.执行删除方法 userDao.deleteUser(48); } /** * 测试删除操作 */ @Test public void testFindOne(){ //5.执行查询一个方法 User user = userDao.findById(50); System.out.println(user); } /** * 测试模糊查询操作 */ @Test public void testFindByName(){ //5.执行查询一个方法 List<User> users = userDao.findByName("%王%"); // List<User> users = userDao.findByName("王"); for(User user : users){ System.out.println(user); } } /** * 测试查询总记录条数 */ @Test public void testFindTotal(){ //5.执行查询一个方法 int count = userDao.findTotal(); System.out.println(count); } /** * 测试使用QueryVo作为查询条件 */ @Test public void testFindByVo(){ QueryVo vo = new QueryVo(); User user = new User(); user.setUserName("%王%"); vo.setUser(user); //5.执行查询一个方法 List<User> users = userDao.findUserByVo(vo); for(User u : users){ System.out.println(u); } } }
====================
end