Mybatis入门-基于xml配置实现单表的增删改查
配置步骤
1.引入Mybatis的jar包
2.编写实体类与DAO接口
3.添加主配置文件(配置mysql环境,事务类型,数据源,连接数据库的基本信息,映射文件的位置)
4.使用mybatis中的注解
5.使用mybatis框架
使用步骤
1.读取配置文件,可使用mybatis封装的Resources类。
2.创建SQLSessionFactory工厂
3.使用工厂生产SQLsession对象
4.使用SQLSession创建DAO接口的代理对象
5.使用代理对象执行方法
6.提交事务,释放资源
实体类
/** * @Author: Promsing * @Date: 2021/4/5 - 9:08 * @Description: User类、Account类 * @version: 1.0 */ public class User implements Serializable { private Integer id; private String username; private String address; private String sex; private Date birthday; //一对多关系映射 一个用户对应多个账户 private List<Account> accounts; public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> account) { this.accounts = account; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", address='" + address + '\'' + ", sex='" + sex + '\'' + ", birthday=" + birthday + '}'; } 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 getAddress() { return address; } public void setAddress(String address) { this.address = address; } 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 class Account implements Serializable { private Integer id; private Integer uid; private Double money; //多对一 每个账户只能属于一个用户 private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", uid=" + uid + ", money=" + money + '}'; } }
DAO接口+注解
/** * @Author: Promsing * @Date: 2021/4/5 - 9:10 * @Description: mybatis:基于注解开发 * @version: 1.0 */ public interface IUserDao { /** * 查询所有用户 * @return */ @Select("select * from User") //当实体类属性与MySQL列名不一致时 //id属性可被其他方法引用--- @ResultMap("userMap") @Results(id="userMap", value = { //主键为true 库中列名 类中属性 @Result(id=true,column = "id",property = "id"), @Result(column = "username",property = "username"), @Result(column = "birthday",property = "birthday"), @Result(column = "sex",property = "sex"), @Result(column = "address",property = "address"), //关系为一对多 延迟加载 @Result(column = "id",property = "accounts", many = @Many( select = "com.dynamic_annotation_real.dao.IAccountDao.findAccountByUid", fetchType = FetchType.LAZY)) }) List<User> findAll(); /** * 查询一个 * @param i * @return */ @Select("select * from user where id=#{id}") User findById(Integer i); /** * 根据名称模糊查询 * @param name * @return */ @Select("select * from user where username like #{name}") List<User> findUserByName(String name); /** * 保存操作 * @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); /** * 查询总行数 * @return */ @Select("select count(id) from user") int findTotalUser(); } public interface IAccountDao { /** * 查询所有 * @return */ @Select("select * from Account") @Results(id="accountMap",value = { @Result(id=true,column = "id",property = "id"), @Result(column = "uid",property = "uid"), @Result(column = "money",property = "money"), //配置立即加载 @Result(property ="user", column = "uid", one = @One( select = "com.dynamic_annotation_real.dao.IUserDao.findById", fetchType = FetchType.EAGER)), }) List<Account> findAll(); /** * 根据用户id查询账户信息 * @param userId * @return */ @Select("select * from Account where uid=#{userId}") List<Account> findAccountByUid(Integer userId); }
主配置文件
<?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"> <!--myBatis的主配置文件 --> <configuration> <!--配置别名--> <typeAliases> <package name="com.dynamic_annotation_real.domain"/> </typeAliases> <!--配置环境--> <environments default="mysql"> <!--配置mysql环境--> <environment id="mysql"> <!--配置事务的类型--> <transactionManager type="JDBC"></transactionManager> <!--配置数据源(连接池)--> <dataSource type="POOLED"> <!--配置连接数据库的基本信息--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/eesy"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!--注解开发--> <mappers> <package name="com.dynamic_annotation_real.dao"></package> </mappers> <!--映射文件 注解方式(使用注解就要删除源配置文件)--> <!-- <mappers> <mapper class="com.dynamic_basics.dao.IUserDao"></mapper> </mappers>--> </configuration>
测试类
public class AnnotationTest { private SqlSession sqlSession; private InputStream in; private IUserDao userDao; private IAccountDao accountDao; @Before public void init() throws Exception{ //1.读取配置文件 in= Resources.getResourceAsStream("SqlMapConfig_realanno.xml"); //2.创建SqlSessionFactory工程 SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in); //3.通过工厂创建SqlSession sqlSession = factory.openSession(); //4.代理模式增强方法 userDao = sqlSession.getMapper(IUserDao.class); accountDao = sqlSession.getMapper(IAccountDao.class); } @After public void destroy() throws Exception{ sqlSession.commit(); sqlSession.close(); in.close(); } @Test public void testFindAll(){ List users = userDao.findAll(); for (User user : users) { System.out.println("---每个用户的账户信息---"); System.out.println(user); System.out.println(user.getAccounts()); } } @Test public void testSaveUser(){ User user=new User(); user.setUsername("alibaba"); user.setAddress("壹号院"); user.setSex("女"); user.setBirthday(new Date()); userDao.saveUser(user); } @Test public void testUpdateUser(){ User user=new User(); user.setUsername("CSDN"); user.setAddress("北京"); user.setSex("男"); user.setBirthday(new Date()); user.setId(45); userDao.updateUser(user); } @Test public void testDelete(){ userDao.deleteUser(53); } @Test public void testFindOne(){ User user = userDao.findById(52); System.out.println(user); //默认开启一级缓存 User user2 = userDao.findById(52); System.out.println(user2); System.out.println(user==user2); } @Test public void testFindByName(){ List users = userDao.findUserByName("%s%"); for (User user : users) { System.out.println(user); } } @Test public void testFindTotal(){ int totalUser = userDao.findTotalUser(); System.out.println(totalUser); } /*注解一对一,一对多*/ @Test public void testAccountFindAll(){ List accounts = accountDao.findAll(); for (Account account : accounts) { System.out.println("---每个账户信息---"); System.out.println(account); System.out.println(account.getUser()); } } }
总结mybatis注解
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result一起使用,封装多个结果集
@ResultMap:实现引用@Results定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装