赞
踩
1、创建数据库表
CREATE DATABASE test; CREATE TABLE `user` ( `id` int(11) NOT NULL auto_increment, `username` varchar(32) NOT NULL COMMENT '用户名称', `birthday` datetime default NULL COMMENT '生日', `sex` char(1) default NULL COMMENT '性别', `address` varchar(256) default NULL COMMENT '地址', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (41,'老王','2018-02-27 17:47:08','男','北京'); insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (42,'小二王','2018-03-02 15:09:37','女','北京金燕龙'); insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (43,'小二王','2018-03-04 11:34:34','女','北京金燕龙'); insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (45,'传智播客','2018-03-04 12:04:06','男','北京金燕龙'); insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (46,'老王','2018-03-07 17:37:26','男','北京'); insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (48,'小马宝莉','2018-03-08 11:44:00','女','北京修正'); CREATE TABLE `account` ( `ID` int(11) NOT NULL COMMENT '编号', `UID` int(11) default NULL COMMENT '用户编号', `MONEY` double default NULL COMMENT '金额', PRIMARY KEY (`ID`), KEY `FK_Reference_8` (`UID`), CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `account`(`ID`,`UID`,`MONEY`) values (1,46,1000),(2,45,1000),(3,46,2000);
2、创建maven工程并导入坐标
3、创建实体类、持久层dao接口
在domain包中创建User类
- package com.wedu.mybatis09.domain;
-
- import java.io.Serializable;
- import java.util.Date;
- import java.util.List;
-
- /**
- * 用户实体
- */
- public class User implements Serializable {
-
- private Integer id;
- private String username;
- private String address;
- private String sex;
- private Date 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;
- }
-
- @Override
- public String toString() {
- return "User{" +
- "id=" + id +
- ", username='" + username + '\'' +
- ", address='" + address + '\'' +
- ", sex='" + sex + '\'' +
- ", birthday=" + birthday +
- '}';
- }
- }
在domain包中创建Account类
- package com.wedu.mybatis09.domain;
-
- import java.io.Serializable;
-
- /**
- * 账户实体
- */
- public class Account implements Serializable {
-
- private Integer id;
- private Integer uid;
- private Double money;
-
- 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包中创建IUserDao接口
- package com.wedu.mybatis09.dao;
-
- /**
- * 用户的持久层接口
- */
- public interface IUserDao {
-
- }
在dao包中创建IAccountDao接口
- package com.wedu.mybatis09.dao;
-
- /**
- * 账户持久层接口
- */
- public interface IAccountDao {
-
- }
4、创建数据库配置文件:jdbc.properties
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&characterEncoding=utf8
- jdbc.username=root
- jdbc.password=123456
5、创建日志文件:log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=debug, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n # LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=E:\\project\\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
6、创建配置文件: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="jdbc.properties"/>
-
- <!--配置别名-->
- <typeAliases>
- <package name="com.wedu.mybatis09.domain"/>
- </typeAliases>
-
- <!--配置环境-->
- <environments default="development">
- <environment id="development">
- <!--配置事务的类型-->
- <transactionManager type="JDBC"></transactionManager>
- <!--配置数据源-->
- <dataSource type="POOLED">
- <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.wedu.mybatis09.dao" />
- </mappers>
- </configuration>
7、创建测试类UserDaoTest和AccountDaoTest
UserDaoTest测试类
- package com.wedu.mybatis09.dao;
-
- 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;
-
- /**
- * 对象关系映射测试
- */
- public class UserDaoTest {
-
- private SqlSession session;
- private IUserDao userDao;
-
- @Before
- public void init() throws Exception{
- SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlMapConfig.xml"));
- session = factory.openSession();
- userDao = session.getMapper(IUserDao.class);
- }
-
- @After
- public void destroy() {
- session.close();
- }
- }
AccountDaoTest测试类
- package com.wedu.mybatis09.dao;
-
- 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;
-
- public class AccountDaoTest {
-
- private SqlSession session;
- private IAccountDao accountDao;
-
- @Before
- public void init() throws Exception{
- SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlMapConfig.xml"));
- session = factory.openSession();
- accountDao = session.getMapper(IAccountDao.class);
- }
-
- @After
- public void destroy() {
- session.close();
- }
- }
- /**
- * 查询所有账户
- */
- @Test
- public void testFindAll() {
- List<Account> accounts = accountDao.findAll();
- for (Account account : accounts) {
- System.out.println(account);
- System.out.println(account.getUser());
- }
- }
1、创建映射文件:IUserDao.xml和IAccountDao.xml
IUserDao.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">
- <mapper namespace="com.wedu.mybatis09.dao.IUserDao">
-
- </mapper>
IAccountDao.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">
- <mapper namespace="com.wedu.mybatis09.dao.IAccountDao">
-
- </mapper>
2、一对一的关系映射
2.1、在Account实体类添加User属性
- //一对一的关系映射:从表实体应该包含一个主表实体的对象引用
- private User user;
-
- public User getUser() {
- return user;
- }
-
- public void setUser(User user) {
- this.user = user;
- }
2.2、在IAccountDao中添加查询方法
- /**
- * 查询所有账户,,同时还要获取到当前账户的所属用户信息
- * @return
- */
- List<Account> findAll();
2.3、在IAccountDao.xml添加sql语句
- <!--定义封装account和user的resultMap-->
- <resultMap id="accountUserMap" type="account">
- <id property="id" column="aid"></id>
- <result property="uid" column="uid"></result>
- <result property="money" column="money"></result>
- <!-- 一对一的关系映射:配置封装user的内容-->
- <association property="user" column="uid" javaType="user">
- <id property="id" column="id"></id>
- <result property="username" column="username"></result>
- <result property="birthday" column="birthday"></result>
- <result property="sex" column="sex"></result>
- <result property="address" column="address"></result>
- </association>
- </resultMap>
- <!-- 查询所有 -->
- <select id="findAll" resultMap="accountUserMap">
- select u.*,a.id as aid,a.uid,a.money from account a , user u where u.id = a.uid;
- </select>
2.4、在AccountDaoTest的测试类中测试
- /**
- * 查询所有账户
- */
- @Test
- public void testFindAll() {
- List<Account> accounts = accountDao.findAll();
- for (Account account : accounts) {
- System.out.println(account);
- System.out.println(account.getUser());
- }
- }
3、一对多(多对一)映射
3.1、在User实体类添加Account属性
- //一对多关系映射:主表实体应该包含从表实体的集合引用
- private List<Account> accounts;
-
- public List<Account> getAccounts() {
- return accounts;
- }
-
- public void setAccounts(List<Account> accounts) {
- this.accounts = accounts;
- }
3.2、在IUserDao中添加查询方法
- /**
- * 查询所有用户,,同时获取到用户下所有账户的信息
- * @return
- */
- List<User> findAll();
3.3、在IUserDao.xml添加sql语句
- <!--定义User的resultMap-->
- <resultMap id="userAccountMap" type="user">
- <id property="id" column="id"></id>
- <result property="username" column="username"></result>
- <result property="birthday" column="birthday"></result>
- <result property="sex" column="sex"></result>
- <result property="address" column="address"></result>
- <!--一对多的关系映射:配置user对象中accounts集合的映射-->
- <collection property="accounts" ofType="account">
- <id property="id" column="aid"></id>
- <result property="uid" column="uid"></result>
- <result property="money" column="money"></result>
- </collection>
- </resultMap>
- <!-- 查询所有 -->
- <select id="findAll" resultMap="userAccountMap">
- select u.*,a.id as aid,a.uid,a.money from user u left outer join account a on u.id = a.uid
- </select>
3.4、在UserDaoTest的测试类中测试
- /**
- * 查询所有用户
- */
- @Test
- public void testFindAll() {
- List<User> users = userDao.findAll();
- for (User user : users) {
- System.out.println(user);
- System.out.println(user.getAccounts());
- }
- }
1、一对一的关系映射
1.1、在Account实体类添加User属性
- //一对一的关系映射:从表实体应该包含一个主表实体的对象引用
- private User user;
-
- public User getUser() {
- return user;
- }
-
- public void setUser(User user) {
- this.user = user;
- }
1.2、在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.wedu.mybatis15.dao.IUserDao.findById",fetchType= FetchType.EAGER))
- })
- List<Account> findAll();
1.3、 在IUserDao接口中添加根据id查询方法
- /**
- * 根据id查询用户
- * @param id
- * @return
- */
- @Select("select * from user where id=#{id}")
- User findById(Integer id);
1.4、在AccountDaoTest的测试类中测试
- /**
- * 查询所有账户
- */
- @Test
- public void testFindAll() {
- List<Account> accounts = accountDao.findAll();
- for (Account account : accounts) {
- System.out.println(account);
- System.out.println(account.getUser());
- }
- }
2、一对多(多对一)映射
1.1、在User实体类添加Account属性
- //一对多关系映射:主表实体应该包含从表实体的集合引用
- private List<Account> accounts;
-
- public List<Account> getAccounts() {
- return accounts;
- }
-
- public void setAccounts(List<Account> accounts) {
- this.accounts = accounts;
- }
1.2、在IUserDao接口中添加关联查询方法并添加多对一的关系映射注解
- /**
- * 查询所有用户
- * @return
- */
- @Select("select * from user")
- @Results(id = "userMap",value = {
- @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(property = "accounts",column = "id",
- many = @Many(select = "com.wedu.mybatis15.dao.IAccountDao.findAccountByUid",
- fetchType = FetchType.LAZY))
- })
- List<User> findAll();
1.3、在IAccountDao接口中添加根据id查询方法
- /**
- * 根据用户id查询账户信息
- * @param id
- * @return
- */
- @Select("select * from account where uid=#{id}")
- Account findAccountByUid(Integer id);
1.3、在UserDaoTest的测试类中测试
- /**
- * 查询所有用户
- */
- @Test
- public void testFindAll() {
- List<User> users = userDao.findAll();
- for (User user : users) {
- System.out.println(user);
- System.out.println(user.getAccounts());
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。