Mybatis环境搭建及测试
1、新建java project,导入相应jar包
本次使用到的mybatis-3.2.7版本
mybatis需要jar包:mybatis-3.2.7.jar、lib文件下的依赖jar
mysql驱动jar包:mysql-connector-java-5.1.7.-bin.jar
2、创建数据库
数据库名:mybatis
数据表:user
3、配置mybaits核心配置文件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> <!-- 和spring整合后 environments配置将废除--> <environments default="development"> <environment id="development"> <!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 --> <transactionManager type="JDBC" /> <!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI --> <!-- POOLED 表示支持JDBC数据源连接池 --> <!-- UNPOOLED 表示不支持数据源连接池 --> <!-- JNDI 表示支持外部数据源连接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="mysqladmin" /> </dataSource> </environment> </environments> <mappers> <mapper resource="User.xml"/> </mappers> </configuration>
SqlMapConfig.xml放入项目中config源文件下
4、创建对应数据表的java实体类
User.java
package cn.itheima.pojo; import java.util.Date; public class User { private int id; private String username;// 用户姓名 private String sex;// 性别 private Date birthday;// 生日 private String address;// 地址 public int getId() { return id; } public void setId(int 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 + "]"; } }
5、创建对应的映射文件
User.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"> <!-- namespace:命名空间,做sql隔离 --> <mapper namespace="test"> <!-- id:sql语句唯一标识 parameterType:指定传入参数类型(pojo类中对应的类型,不是数据库中的类型) resultType:返回结果集类型 #{}:占位符,如果传入的类型是基本类型(string,long,double,int,boolean,float等),那么#{}中变量名称可以任意 --> <select id="findUserById" parameterType="java.lang.Integer" resultType="cn.itheima.pojo.User"> SELECT * FROM user WHERE id=#{id} </select> <!-- 如果返回的结果为集合,resultType中也是配置为集合中泛型的类型,即resultType="cn.itheima.pojo.User" ${}:拼接符,如果传入的类型是基本类型(string,long,double,int,boolean,float等),那么${}中变量名称必须是value --> <select id="findUserByUserName" parameterType="java.lang.String" resultType="cn.itheima.pojo.User"> SELECT * FROM user WHERE username LIKE '%${value}%' </select> <!-- 如果传入的是pojo类型,则#{}中变量名称必须是pojo中对应的属性.属性.属性...... 如果要返回数据库自增主键,可以使用SELECT LAST_INSERT_ID() --> <insert id="insertUser" parameterType="cn.itheima.pojo.User"> <!-- 执行SELECT LAST_INSERT_ID()数据库函数,返回自增的主键 keyProperty:将返回的主键放入传入的参数的Id中保存(保存到user对象中的id属性) order:当前函数相对于insert语句的执行顺序,在insert前执行用BEFORE,在insert后执行用AFTER resultType:id的类型,也就是keyProperty中属性类型 --> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO user (username,birthday,sex,address) VALUES (#{username},#{birthday},#{sex},#{address}) </insert> <delete id="deleteUserById" parameterType="java.lang.Integer"> DELETE FROM user WHERE id=#{id} </delete> <update id="updateUserById" parameterType="cn.itheima.pojo.User"> UPDATE user SET username=#{username} WHERE id=#{id} </update> </mapper>
二、测试
package mybatis0523; import java.io.InputStream; import java.util.Date; import java.util.List; 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 cn.itheima.pojo.User; public class UserTest { @Test public void testFindUserById() throws Exception { String resource = "SqlMapConfig.xml"; // 通过流将核心配置文件读取进来 InputStream inputStream = Resources.getResourceAsStream(resource); // 通过核心配置文件创建会话工厂 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); // 通过会话工厂创建会话 SqlSession session = factory.openSession(); User user = session.selectOne("test.findUserById", 1); System.out.println(user); } @Test public void testFindUserByUserName() throws Exception { String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = factory.openSession(); List<User> list = session.selectList("test.findUserByUserName", "王"); System.out.println(list); } @Test public void testInsertUser() throws Exception { String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = factory.openSession(); User user = new User(); user.setUsername("赵四"); user.setBirthday(new Date()); user.setSex("1"); user.setAddress("北京昌平"); System.out.println(user.getId()); session.insert("test.insertUser", user); // mybatis中事务默认是开启的,所以在mybatis中不需要显式开启事务,只需要显式提交事务 // 提交事务 session.commit(); System.out.println(user.getId()); } @Test public void testDeleteUserById() throws Exception { String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = factory.openSession(); session.delete("test.deleteUserById", 27); session.commit(); } @Test public void testUpdateUserById() throws Exception { String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = factory.openSession(); User user = new User(); user.setUsername("赵四"); user.setId(24); session.update("test.updateUserById", user); session.commit(); } }
简单的mybatis环境搭建和测试已完成,整个目录结构如下