创建步骤:
-
创建maven工程,什么都不选就ok,并导入坐标;
<packaging>jar</packaging> <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>5.1.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> </dependencies>
-
编写User实体类,java目录下创建com.ben.domain包,创建User实体类
public class User implements Serializable { 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 + "]"; } }
-
使用注解方式编写持久层接口
package com.ben.dao; import com.ben.domain.User; import org.apache.ibatis.annotations.*; import java.util.List; /** * @ClassName: IUserDao * @author: benjamin * @createTime: 2019/07/19/21:50 */ public interface IUserDao { /** * @Description: 增加用户 * @Param: User user:类对象 * @return: int * @Author: benjamin * @Date: 2019/7/19 */ @Insert("insert into user(username,sex,birthday,address) values (#{username},#{sex},#{birthday},#{address})") int insertUser(User user); /** * @Description: 删除用户 * @Param: * @return: * @Author: benjamin * @Date: 2019/7/19 */ @Delete("delete from user where id=#{id}") int deleteUser(Integer id); /** * @Description: 修改用户 * @Param: * @return: * @Author: benjamin * @Date: 2019/7/19 */ @Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id =#{id}") int updateUser(User user); /** * @Description: 查询所有用户 * @Param: * @return: * @Author: benjamin * @Date: 2019/7/19 */ @Select("select * from user") @Results(id="userMap", value = { @Result(id=true,column = "id",property = "id"), @Result(column = "username", property = "username"), @Result(column = "sex", property = "sex"), @Result(column = "address", property = "address"), @Result(column = "birthday", property = "birthday") }) List<User> findAll(); /** * @Description: 根据用户ID查询用户 * @Param: * @return: * @Author: benjamin * @Date: 2019/7/19 */ @Select("select * from user where id = #{id}") User findUserById(Integer id); /** * @Description: 根据用户名模糊查询用户 * @Param: * @return: * @Author: benjamin * @Date: 2019/7/19 */ // @Select("select * from user where username like #{username}") @Select("select * from user where username like '%${value}%'") List<User> findUserByUserName(String username); /** * @Description: 查询用户的总数 * @Param: * @return: * @Author: benjamin * @Date: 2019/7/19 */ @Select("select count(*) from user") int findTotalUser(); }
-
在resources文件夹中,创建Mybatis的主配置文件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="jdbcConfig.properties"></properties> <!--配置别名--> <typeAliases> <package name="com.ben.domain"/> </typeAliases> <!-- 配置环境--> <environments default="mysql"> <!--配置mysql的环境--> <environment id="mysql"> <!--配置事务的类型--> <transactionManager type="JDBC"></transactionManager> <!--配置连接池--> <dataSource type="POOLED"> <!--配置连接数据库的4个基本信息--> <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> <package name="com.ben.dao"/> </mappers> </configuration>
-
在resources文件夹中导入log4j.properties文件
-
编写测试类com.ben.test.AnnotationTest,6步;
1.读取配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); 2.创建SqlSessionFactory工厂 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); 3.创建SqlSession工厂对象 SqlSessionFactory factory = builder.build(in); 4.使用工厂生产SqlSession对象 session = factory.openSession(); 5.创建Dao接口的代理对象 userdao = session.getMapper(IUserDao.class); 6.执行操作:增删改查等操作 7.释放资源 session.commit(); session.close(); in.close();
测试类编写:
public class AnnotationTest { 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(true); //4.获取dao的代理对象 userDao = sqlSession.getMapper(IUserDao.class); } @After//用于在测试方法执行之后执行 public void destroy()throws Exception{ //提交事务 sqlSession.commit(); //6.释放资源 sqlSession.close(); in.close(); } //增加用户 @Test public void testSaveUser(){ User user = new User(); user.setUsername("笑笑"); user.setSex("2"); user.setBirthday(new Date()); user.setAddress("西安市雁塔区"); int i = userDao.insertUser(user); System.out.println("插入ID:"+user.getId()); } //删除用户 @Test public void testDeleteUser(){ int i = userDao.deleteUser(40); System.out.println(i); } //修改用户 @Test public void testUpdateUser(){ User user = new User(); user.setUsername("笑笑"); user.setBirthday(new Date()); user.setAddress("西安市雁塔区"); user.setId(41); userDao.updateUser(user); } //测试查询所有 @Test public void testFindAll(){ List<User> users = userDao.findAll(); for(User user : users){ System.out.println(user); } } //根据用户ID查找用户 @Test public void testFindUserById(){ User userById = userDao.findUserById(41); System.out.println(userById); } //根据用户名模糊查找用户 @Test public void testFindUserByUserName(){ // List<User> list = userDao.findUserByUserName("%王%"); //#{} List<User> list = userDao.findUserByUserName("王"); //字符串拼接 for(User user:list){ System.out.println(user); } } //查找用户的总数 @Test public void testTotalCount(){ int totalUser = userDao.findTotalUser(); System.out.println(totalUser); } }