1编写实体类
public class User implements Serializable { private Integer userId; private String userName; private Date userBirthday; private String userSex; private String userAddress; 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 Date getUserBirthday() { return userBirthday; } public void setUserBirthday(Date userBirthday) { this.userBirthday = userBirthday; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } @Override public String toString() { return "User [userId=" + userId + ", userName=" + userName + ", userBirthday=" + userBirthday + ", userSex=" + userSex + ", userAddress=" + userAddress + "]"; } }
注意:
此处我们故意和数据库表的列名不一致
2.使用注解方式开发持久层接口
package com.itheima.dao; import com.itheima.domain.User; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; /** * @author 黑马程序员 * @Company http://www.ithiema.com * 在mybatis中针对,CRUD一共有四个注解 * @Select @Insert @Update @Delete */ public interface IUserDao { /** * 查询所有用户 * @return */ @Select("select * from user") List<User> findAll(); /** * 保存用户 * @param user */ @Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})") void saveUser(User user); /** * 更新用户 * @param user */ @Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}") void updateUser(User user); /** * 删除用户 * @param userId */ @Delete("delete from user where id=#{id} ") void deleteUser(Integer userId); /** * 根据id查询用户 * @param userId * @return */ @Select("select * from user where id=#{id} ") User findById(Integer userId); /** * 根据用户名称模糊查询 * @param username * @return */ // @Select("select * from user where username like #{username} ") @Select("select * from user where username like '%${value}%' ") List<User> findUserByName(String username); /** * 查询总用户数量 * @return */ @Select("select count(*) from user ") int findTotalUser(); }
通过注解方式,我们就不需要再去编写 UserDao.xml 映射文件了。
3/编写 SqlMapConfig 配置文件
<?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.itheima.domain"></package> </typeAliases> <!-- 配置环境--> <environments default="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> <!-- 指定带有注解的dao接口所在位置 --> <mappers> <mapper class="com.itheima.dao.IUserDao"></mapper> </mappers> </configuration>
4.编写测试方法
package com.itheima.test; import com.itheima.dao.IUserDao; 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 */ public class AnnotationCRUDTest { private InputStream in; private SqlSessionFactory factory; private SqlSession session; private IUserDao userDao; @Before public void init()throws Exception{ in = Resources.getResourceAsStream("SqlMapConfig.xml"); factory = new SqlSessionFactoryBuilder().build(in); session = factory.openSession(); userDao = session.getMapper(IUserDao.class); } @After public void destroy()throws Exception{ session.commit(); session.close(); in.close(); } @Test public void testSave(){ User user = new User(); user.setUsername("mybatis annotation"); user.setAddress("北京市昌平区"); userDao.saveUser(user); } @Test public void testUpdate(){ User user = new User(); user.setId(57); user.setUsername("mybatis annotation update"); user.setAddress("北京市海淀区"); user.setSex("男"); user.setBirthday(new Date()); userDao.updateUser(user); } @Test public void testDelete(){ userDao.deleteUser(51); } @Test public void testFindOne(){ User user = userDao.findById(57); System.out.println(user); } @Test public void testFindByName(){ // List<User> users = userDao.findUserByName("%mybatis%"); List<User> users = userDao.findUserByName("mybatis"); for(User user : users){ System.out.println(user); } } @Test public void testFindTotal(){ int total = userDao.findTotalUser(); System.out.println(total); } }