当前位置:   article > 正文

Mybatis框架(十):Mybatis的对象关系映射(一)_mybatis映射创建对象

mybatis映射创建对象

一、对象关系映射环境搭建

1、创建数据库表

  1. CREATE DATABASE test;
  2. CREATE TABLE `user` (
  3. `id` int(11) NOT NULL auto_increment,
  4. `username` varchar(32) NOT NULL COMMENT '用户名称',
  5. `birthday` datetime default NULL COMMENT '生日',
  6. `sex` char(1) default NULL COMMENT '性别',
  7. `address` varchar(256) default NULL COMMENT '地址',
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  10. insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (41,'老王','2018-02-27 17:47:08','男','北京');
  11. insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (42,'小二王','2018-03-02 15:09:37','女','北京金燕龙');
  12. insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (43,'小二王','2018-03-04 11:34:34','女','北京金燕龙');
  13. insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (45,'传智播客','2018-03-04 12:04:06','男','北京金燕龙');
  14. insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (46,'老王','2018-03-07 17:37:26','男','北京');
  15. insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (48,'小马宝莉','2018-03-08 11:44:00','女','北京修正');
  16. CREATE TABLE `account` (
  17. `ID` int(11) NOT NULL COMMENT '编号',
  18. `UID` int(11) default NULL COMMENT '用户编号',
  19. `MONEY` double default NULL COMMENT '金额',
  20. PRIMARY KEY (`ID`),
  21. KEY `FK_Reference_8` (`UID`),
  22. CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
  23. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  24. insert into `account`(`ID`,`UID`,`MONEY`) values (1,46,1000),(2,45,1000),(3,46,2000);

2、创建maven工程并导入坐标

3、创建实体类、持久层dao接口

在domain包中创建User类

  1. package com.wedu.mybatis09.domain;
  2. import java.io.Serializable;
  3. import java.util.Date;
  4. import java.util.List;
  5. /**
  6. * 用户实体
  7. */
  8. public class User implements Serializable {
  9. private Integer id;
  10. private String username;
  11. private String address;
  12. private String sex;
  13. private Date birthday;
  14. public Integer getId() {
  15. return id;
  16. }
  17. public void setId(Integer id) {
  18. this.id = id;
  19. }
  20. public String getUsername() {
  21. return username;
  22. }
  23. public void setUsername(String username) {
  24. this.username = username;
  25. }
  26. public String getAddress() {
  27. return address;
  28. }
  29. public void setAddress(String address) {
  30. this.address = address;
  31. }
  32. public String getSex() {
  33. return sex;
  34. }
  35. public void setSex(String sex) {
  36. this.sex = sex;
  37. }
  38. public Date getBirthday() {
  39. return birthday;
  40. }
  41. public void setBirthday(Date birthday) {
  42. this.birthday = birthday;
  43. }
  44. @Override
  45. public String toString() {
  46. return "User{" +
  47. "id=" + id +
  48. ", username='" + username + '\'' +
  49. ", address='" + address + '\'' +
  50. ", sex='" + sex + '\'' +
  51. ", birthday=" + birthday +
  52. '}';
  53. }
  54. }

在domain包中创建Account类

  1. package com.wedu.mybatis09.domain;
  2. import java.io.Serializable;
  3. /**
  4. * 账户实体
  5. */
  6. public class Account implements Serializable {
  7. private Integer id;
  8. private Integer uid;
  9. private Double money;
  10. public Integer getId() {
  11. return id;
  12. }
  13. public void setId(Integer id) {
  14. this.id = id;
  15. }
  16. public Integer getUid() {
  17. return uid;
  18. }
  19. public void setUid(Integer uid) {
  20. this.uid = uid;
  21. }
  22. public Double getMoney() {
  23. return money;
  24. }
  25. public void setMoney(Double money) {
  26. this.money = money;
  27. }
  28. @Override
  29. public String toString() {
  30. return "Account{" +
  31. "id=" + id +
  32. ", uid=" + uid +
  33. ", money=" + money +
  34. '}';
  35. }
  36. }

在dao包中创建IUserDao接口

  1. package com.wedu.mybatis09.dao;
  2. /**
  3. * 用户的持久层接口
  4. */
  5. public interface IUserDao {
  6. }

在dao包中创建IAccountDao接口

  1. package com.wedu.mybatis09.dao;
  2. /**
  3. * 账户持久层接口
  4. */
  5. public interface IAccountDao {
  6. }

4、创建数据库配置文件:jdbc.properties

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=utf8
  3. jdbc.username=root
  4. jdbc.password=123456

5、创建日志文件:log4j.properties

  1. # Set root category priority to INFO and its only appender to CONSOLE.
  2. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
  3. log4j.rootCategory=debug, CONSOLE, LOGFILE
  4. # Set the enterprise logger category to FATAL and its only appender to CONSOLE.
  5. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
  6. # CONSOLE is set to be a ConsoleAppender using a PatternLayout.
  7. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
  8. log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
  9. log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
  10. # LOGFILE is set to be a File appender using a PatternLayout.
  11. log4j.appender.LOGFILE=org.apache.log4j.FileAppender
  12. log4j.appender.LOGFILE.File=E:\\project\\axis.log
  13. log4j.appender.LOGFILE.Append=true
  14. log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
  15. log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

6、创建配置文件:SqlMapConfig.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!--引用外部的配置文件信息-->
  7. <properties resource="jdbc.properties"/>
  8. <!--配置别名-->
  9. <typeAliases>
  10. <package name="com.wedu.mybatis09.domain"/>
  11. </typeAliases>
  12. <!--配置环境-->
  13. <environments default="development">
  14. <environment id="development">
  15. <!--配置事务的类型-->
  16. <transactionManager type="JDBC"></transactionManager>
  17. <!--配置数据源-->
  18. <dataSource type="POOLED">
  19. <property name="driver" value="${jdbc.driver}"/>
  20. <property name="url" value="${jdbc.url}"/>
  21. <property name="username" value="${jdbc.username}"/>
  22. <property name="password" value="${jdbc.password}"/>
  23. </dataSource>
  24. </environment>
  25. </environments>
  26. <!--配置映射文件的位置-->
  27. <mappers>
  28. <package name="com.wedu.mybatis09.dao" />
  29. </mappers>
  30. </configuration>

7、创建测试类UserDaoTest和AccountDaoTest

UserDaoTest测试类

  1. package com.wedu.mybatis09.dao;
  2. import org.apache.ibatis.io.Resources;
  3. import org.apache.ibatis.session.SqlSession;
  4. import org.apache.ibatis.session.SqlSessionFactory;
  5. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  6. import org.junit.After;
  7. import org.junit.Before;
  8. /**
  9. * 对象关系映射测试
  10. */
  11. public class UserDaoTest {
  12. private SqlSession session;
  13. private IUserDao userDao;
  14. @Before
  15. public void init() throws Exception{
  16. SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlMapConfig.xml"));
  17. session = factory.openSession();
  18. userDao = session.getMapper(IUserDao.class);
  19. }
  20. @After
  21. public void destroy() {
  22. session.close();
  23. }
  24. }

AccountDaoTest测试类 

  1. package com.wedu.mybatis09.dao;
  2. import org.apache.ibatis.io.Resources;
  3. import org.apache.ibatis.session.SqlSession;
  4. import org.apache.ibatis.session.SqlSessionFactory;
  5. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  6. import org.junit.After;
  7. import org.junit.Before;
  8. public class AccountDaoTest {
  9. private SqlSession session;
  10. private IAccountDao accountDao;
  11. @Before
  12. public void init() throws Exception{
  13. SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlMapConfig.xml"));
  14. session = factory.openSession();
  15. accountDao = session.getMapper(IAccountDao.class);
  16. }
  17. @After
  18. public void destroy() {
  19. session.close();
  20. }
  21. }
  1. /**
  2. * 查询所有账户
  3. */
  4. @Test
  5. public void testFindAll() {
  6. List<Account> accounts = accountDao.findAll();
  7. for (Account account : accounts) {
  8. System.out.println(account);
  9. System.out.println(account.getUser());
  10. }
  11. }

二、mybatis基于XML的对象关系映射的实现

1、创建映射文件:IUserDao.xml和IAccountDao.xml

IUserDao.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.wedu.mybatis09.dao.IUserDao">
  6. </mapper>

IAccountDao.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.wedu.mybatis09.dao.IAccountDao">
  6. </mapper>

2、一对一的关系映射

2.1、在Account实体类添加User属性

  1. //一对一的关系映射:从表实体应该包含一个主表实体的对象引用
  2. private User user;
  3. public User getUser() {
  4. return user;
  5. }
  6. public void setUser(User user) {
  7. this.user = user;
  8. }

2.2、在IAccountDao中添加查询方法

  1. /**
  2. * 查询所有账户,,同时还要获取到当前账户的所属用户信息
  3. * @return
  4. */
  5. List<Account> findAll();

2.3、在IAccountDao.xml添加sql语句

  1. <!--定义封装account和user的resultMap-->
  2. <resultMap id="accountUserMap" type="account">
  3. <id property="id" column="aid"></id>
  4. <result property="uid" column="uid"></result>
  5. <result property="money" column="money"></result>
  6. <!-- 一对一的关系映射:配置封装user的内容-->
  7. <association property="user" column="uid" javaType="user">
  8. <id property="id" column="id"></id>
  9. <result property="username" column="username"></result>
  10. <result property="birthday" column="birthday"></result>
  11. <result property="sex" column="sex"></result>
  12. <result property="address" column="address"></result>
  13. </association>
  14. </resultMap>
  15. <!-- 查询所有 -->
  16. <select id="findAll" resultMap="accountUserMap">
  17. select u.*,a.id as aid,a.uid,a.money from account a , user u where u.id = a.uid;
  18. </select>

 2.4、在AccountDaoTest的测试类中测试

  1. /**
  2. * 查询所有账户
  3. */
  4. @Test
  5. public void testFindAll() {
  6. List<Account> accounts = accountDao.findAll();
  7. for (Account account : accounts) {
  8. System.out.println(account);
  9. System.out.println(account.getUser());
  10. }
  11. }

3、一对多(多对一)映射

3.1、在User实体类添加Account属性

  1. //一对多关系映射:主表实体应该包含从表实体的集合引用
  2. private List<Account> accounts;
  3. public List<Account> getAccounts() {
  4. return accounts;
  5. }
  6. public void setAccounts(List<Account> accounts) {
  7. this.accounts = accounts;
  8. }

3.2、在IUserDao中添加查询方法

  1. /**
  2. * 查询所有用户,,同时获取到用户下所有账户的信息
  3. * @return
  4. */
  5. List<User> findAll();

3.3、在IUserDao.xml添加sql语句

  1. <!--定义User的resultMap-->
  2. <resultMap id="userAccountMap" type="user">
  3. <id property="id" column="id"></id>
  4. <result property="username" column="username"></result>
  5. <result property="birthday" column="birthday"></result>
  6. <result property="sex" column="sex"></result>
  7. <result property="address" column="address"></result>
  8. <!--一对多的关系映射:配置user对象中accounts集合的映射-->
  9. <collection property="accounts" ofType="account">
  10. <id property="id" column="aid"></id>
  11. <result property="uid" column="uid"></result>
  12. <result property="money" column="money"></result>
  13. </collection>
  14. </resultMap>
  15. <!-- 查询所有 -->
  16. <select id="findAll" resultMap="userAccountMap">
  17. select u.*,a.id as aid,a.uid,a.money from user u left outer join account a on u.id = a.uid
  18. </select>

3.4、在UserDaoTest的测试类中测试

  1. /**
  2. * 查询所有用户
  3. */
  4. @Test
  5. public void testFindAll() {
  6. List<User> users = userDao.findAll();
  7. for (User user : users) {
  8. System.out.println(user);
  9. System.out.println(user.getAccounts());
  10. }
  11. }

三、mybatis基于注解的对象关系映射的实现

1、一对一的关系映射

1.1、在Account实体类添加User属性

  1. //一对一的关系映射:从表实体应该包含一个主表实体的对象引用
  2. private User user;
  3. public User getUser() {
  4. return user;
  5. }
  6. public void setUser(User user) {
  7. this.user = user;
  8. }

1.2、在IAccountDao接口中添加查询方法并添加一对一的关系映射的注解

  1. /**
  2. * 查询所有账户
  3. * @return
  4. */
  5. @Select("select * from account")
  6. @Results(id = "accountMap",value = {
  7. @Result(id = true,column = "id",property = "id"),
  8. @Result(column = "uid",property = "uid"),
  9. @Result(column = "money",property = "money"),
  10. @Result(property = "user",column = "uid",one=@One(select="com.wedu.mybatis15.dao.IUserDao.findById",fetchType= FetchType.EAGER))
  11. })
  12. List<Account> findAll();

1.3、 在IUserDao接口中添加根据id查询方法

  1. /**
  2. * 根据id查询用户
  3. * @param id
  4. * @return
  5. */
  6. @Select("select * from user where id=#{id}")
  7. User findById(Integer id);

1.4、在AccountDaoTest的测试类中测试

  1. /**
  2. * 查询所有账户
  3. */
  4. @Test
  5. public void testFindAll() {
  6. List<Account> accounts = accountDao.findAll();
  7. for (Account account : accounts) {
  8. System.out.println(account);
  9. System.out.println(account.getUser());
  10. }
  11. }

2、一对多(多对一)映射

1.1、在User实体类添加Account属性

  1. //一对多关系映射:主表实体应该包含从表实体的集合引用
  2. private List<Account> accounts;
  3. public List<Account> getAccounts() {
  4. return accounts;
  5. }
  6. public void setAccounts(List<Account> accounts) {
  7. this.accounts = accounts;
  8. }

1.2、在IUserDao接口中添加关联查询方法并添加多对一的关系映射注解

  1. /**
  2. * 查询所有用户
  3. * @return
  4. */
  5. @Select("select * from user")
  6. @Results(id = "userMap",value = {
  7. @Result(id = true,column = "id",property = "id"),
  8. @Result(column = "username",property = "username"),
  9. @Result(column = "birthday",property = "birthday"),
  10. @Result(column = "sex",property = "sex"),
  11. @Result(column = "address",property = "address"),
  12. @Result(property = "accounts",column = "id",
  13. many = @Many(select = "com.wedu.mybatis15.dao.IAccountDao.findAccountByUid",
  14. fetchType = FetchType.LAZY))
  15. })
  16. List<User> findAll();

1.3、在IAccountDao接口中添加根据id查询方法

  1. /**
  2. * 根据用户id查询账户信息
  3. * @param id
  4. * @return
  5. */
  6. @Select("select * from account where uid=#{id}")
  7. Account findAccountByUid(Integer id);

1.3、在UserDaoTest的测试类中测试

  1. /**
  2. * 查询所有用户
  3. */
  4. @Test
  5. public void testFindAll() {
  6. List<User> users = userDao.findAll();
  7. for (User user : users) {
  8. System.out.println(user);
  9. System.out.println(user.getAccounts());
  10. }
  11. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/625627
推荐阅读
相关标签
  

闽ICP备14008679号