Mybatis基础入门学习
Mybatis基础入门学习
mybatis架构分析
搭建测试mybatis架构
(1)下载并导入mybatis3.2.7.jar(架构),mysql-connector-java-5.1.7-bin.jar(数据库驱动),junit-4.9.jar(单元测试)
(2)测试mybatis项目搭建
(3)Jdbc资源文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3307/mybatis?characterEncoding=utf-8 jdbc.username=root jdbc.password=admins
(4)Mybatis核心配置文件
<?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="jdbc.properties"/> <!-- 别名:方便映射文件调用 --> <typeAliases> <!-- 这个有弊端:有多少pojo就要配置多少个 --> <!--<typeAlias type="com.pojo.User" alias="user"/>--> <!-- 所以用包的方式:扫描该包及其子包的所有pojo,并取别名为(如:user或User) --> <package name="com.pojo"/> </typeAliases> <!-- 数据库环境,与Spring整合后,environments标签将废除--> <environments default="development"> <environment id="development"> <!-- 使用JDBC事务管理 --> <transactionManager type="JDBC"/> <!-- 数据库连接池 --> <dataSource type="POOLED"> <!--<property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="admins"/>--> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!-- 映射器的位置 --> <mappers> <!--<mapper resource="com/mapper/UserMapper.xml"/>--> <!-- 3个属性只能取一个,当为class时,xml文件和接口文件必须文件名一样且在同一个包下 --> <!--<mapper class="com.mapper.UserMapper"/>--> <!-- url:该属性指定mapper在盘符下的绝对路径,不建议使用 --> <!-- 上面的弊端还是会太多配置,导包的原则和class一样 --> <package name="com.mapper"/> </mappers> </configuration>
(5)日志文件
#日志文件 log4j.rootLogger=DEBUG,stdout log4j.logger.org.mybatis=DEBUG log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
(6)创建一个User类
package com.pojo; import java.io.Serializable; import java.util.Date; /** * Serializable:序列化接口 */ public class User implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String username;// 用户姓名 private String sex;// 性别 private Date birthday;// 生日 private String address;// 地址 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 getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address + "]"; } }
(7)User类的映射器
<?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"> <!-- 命名空间:用于区分;如test.findUserById --> <mapper namespace="com.mapper.UserMapper"> <!-- 通过ID查询一个用户 --> <select id="findUserById" parameterType="Integer" resultType="User"> <!-- #{}:表示占位符 --> select * from user where id=#{v} </select> <!-- 根据用户名模糊查询用户 --> <select id="findUserByName" parameterType="String" resultType="com.pojo.User"> <!-- ${}:表示字符串拼接 --> -- select * from user where username like '%${value}%' <!-- 防sql注入 --> select * from user where username like "%"#{value}"%" </select> <!-- 添加用户 --> <insert id="addUser" parameterType="com.pojo.User"> <!-- 获取最新的ID主键 --> <selectKey keyProperty="id" resultType="Integer" order="AFTER"> select LAST_INSERT_ID() </selectKey> insert into user (username,birthday,address,sex) values (#{username},#{birthday},#{address},#{sex}) </insert> <!-- 更新用户 --> <update id="updateUserById" parameterType="com.pojo.User"> update user set username=#{username},birthday=#{birthday},address=#{address},sex=#{sex} where id=#{id} </update> <!-- 删除用户 --> <delete id="delUserById" parameterType="Integer"> delete from user where id=#{id} </delete> </mapper>
(8)与映射器绑定的接口
package com.mapper; import com.pojo.User; /** * @author: XDZY * @date: 2018/8/30 10:02 * @description: 实现用户增删改查的接口(映射器) * 遵循四个原则 * 1)接口方法名与xml文件标签id一样 * 2)方法返回值类型与xml文件一样 * 3)方法的参数与xml文件一样 * 4)xml文件命名空间与该接口绑定 */ public interface UserMapper { public User findUserById(Integer id); }
(9)测试mybatis实现增删改查
package com.junit; import com.pojo.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 java.io.InputStream; import java.util.Date; import java.util.List; /** * @author: XDZY * @date: 2018/8/29 23:18 * @description: 单元测试mybatis的增删改查 */ public class UnitTest { //根据用户ID查询用户 @Test public void testMybatis() throws Exception{ //加载核心配置文件 String resource="sqlMapConfig.xml"; InputStream in= Resources.getResourceAsStream(resource); //创建sqlSessionFactory SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in); //创建sqlSession SqlSession sqlSession=sqlSessionFactory.openSession(); //执行sql语句 User user=sqlSession.selectOne("com.mapper.UserMapper.findUserById",10); System.out.println(user); } //根据用户名模糊查询用户 @Test public void testFindUserByName() throws Exception{ //加载核心配置文件 String resource="sqlMapConfig.xml"; InputStream in= Resources.getResourceAsStream(resource); //创建sqlSessionFactory SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in); //创建sqlSession SqlSession sqlSession=sqlSessionFactory.openSession(); //执行sql语句 List<User> users=sqlSession.selectList("com.mapper.UserMapper.findUserByName","五"); for (User user:users){ System.out.println(user); } } //添加用户 @Test public void testAddUser() throws Exception{ //加载核心配置文件 String resource="sqlMapConfig.xml"; InputStream in= Resources.getResourceAsStream(resource); //创建sqlSessionFactory SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in); //创建sqlSession SqlSession sqlSession=sqlSessionFactory.openSession(); //执行sql语句 User user=new User(); user.setUsername("judy"); user.setSex("男"); user.setBirthday(new Date()); user.setAddress("珠海"); int i=sqlSession.insert("com.mapper.UserMapper.addUser",user); //提交事务 sqlSession.commit(); System.out.println(user.getId()); } //更新用户 @Test public void testUpdateUserById() throws Exception{ //加载核心配置文件 String resource="sqlMapConfig.xml"; InputStream in= Resources.getResourceAsStream(resource); //创建sqlSessionFactory SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in); //创建sqlSession SqlSession sqlSession=sqlSessionFactory.openSession(); //执行sql语句 User user=new User(); user.setId(28); user.setUsername("judy"); user.setSex("女"); user.setBirthday(new Date()); user.setAddress("珠海"); int i=sqlSession.update("com.mapper.UserMapper.updateUserById",user); //提交事务 sqlSession.commit(); } //删除用户 @Test public void testDelUserById() throws Exception{ //加载核心配置文件 String resource="sqlMapConfig.xml"; InputStream in= Resources.getResourceAsStream(resource); //创建sqlSessionFactory SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in); //创建sqlSession SqlSession sqlSession=sqlSessionFactory.openSession(); //执行sql语句 sqlSession.delete("com.mapper.UserMapper.delUserById",28); //提交事务 sqlSession.commit(); } }