第五章:MyBatis注解开发
一、基于注解的CURD
注解 | 说明 |
---|
@Insert | 增加 | @Update | 修改 | @Delete | 删除 | @Select | 查询 | @Result | 结果集封装 | @Results | 多个结果集封装 | @One | 1v1结果集封装 | @Many | 1vN结果集封装 |
1.xml文件映射
package com.itcast.domain;
import java.util.Date;
public class User {
private int id;
private String username;
private String password;
private Date birthday;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
'}';
}
}
package com.itcast.mapper;
import com.itcast.domain.User;
import java.util.List;
public interface UserMapper {
public void save(User user);
public void update(User user);
public void delete(int id);
public User findById(int id);
public List<User> findAll();
}
<?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.itcast.mapper.UserMapper">
<insert id="save" parameterType="user">
insert into user values(#{id}, #{username}, #{password}, #{birthday})
</insert>
<update id="update" parameterType="user">
update user set username = #{username}, password = #{password} where id = #{id}
</update>
<delete id="delete" parameterType="int">
delete from user where id = #{id}
</delete>
<select id="findById" parameterType="int" resultType="user">
select * from user where id = #{id}
</select>
<select id="findAll" resultType="user">
select * from user
</select>
</mapper>
<?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>
<typeAliases>
<typeAlias type="com.itcast.domain.User" alias="user"></typeAlias>
</typeAliases>
<typeHandlers>
<typeHandler handler="com.itcast.handler.DateTypeHandler"></typeHandler>
</typeHandlers>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="20001201"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com.itcast.mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
package com.itcast.test;
import com.itcast.domain.User;
import com.itcast.mapper.UserMapper;
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.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
public class MybatisTest {
private UserMapper mapper;
@Before
public void before() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
mapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void testSave() {
User user = new User();
user.setUsername("Tom");
user.setPassword("1234456");
user.setBirthday(new Date());
mapper.save(user);
}
@Test
public void testUpdate() {
User user = new User();
user.setId(7);
user.setUsername("Lucy");
user.setPassword("abcdefg");
user.setBirthday(new Date());
mapper.update(user);
}
@Test
public void testDelete() {
mapper.delete(8);
}
@Test
public void testFindById() {
User user = mapper.findById(3);
System.out.println(user);
}
@Test
public void testFindAll() {
List<User> userList = mapper.findAll();
for (User user : userList) {
System.out.println(user);
}
}
}
2.注解实现映射
通过注解同样能够实现映射POJO对象和数据表之间的关联映射,对xml文件实现的映射进行修改:
- step1:修改UserMapper文件,将xml文件中的映射以注解的形式写入UserMapper接口中(resources下的xml文件已无用)
package com.itcast.mapper;
import com.itcast.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;
public interface UserMapper {
@Insert("insert into user values(#{id}, #{username}, #{password}, #{birthday})")
public void save(User user);
@Update("update user set username = #{username}, password = #{password} where id = #{id}")
public void update(User user);
@Delete("delete from user where id = #{id}")
public void delete(int id);
@Select("select * from user where id = #{id}")
public User findById(int id);
@Select("select * from user")
public List<User> findAll();
}
- step2:对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>
<typeAliases>
<typeAlias type="com.itcast.domain.User" alias="user"></typeAlias>
</typeAliases>
<typeHandlers>
<typeHandler handler="com.itcast.handler.DateTypeHandler"></typeHandler>
</typeHandlers>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="20001201"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.itcast.mapper"/>
</mappers>
</configuration>
全部修改完成,进行test测试如下:
二、基于注解的关联查询
1.1v1查询
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户。
一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户。
SELECT *, o.id oid
FROM orders o, user u
WHERE o.uid = u.id
(1)配置方式:
配置方式1:
package com.itcast.mapper;
import com.itcast.domain.Order;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface OrderMapper {
@Select("SELECT *, o.id oid FROM orders o, user u WHERE o.uid = u.id")
@Results({
@Result(column = "oid", property = "id"),
@Result(column = "ordertime", property = "ordertime"),
@Result(column = "total", property = "total"),
@Result(column = "uid", property = "user.id"),
@Result(column = "username", property = "user.username"),
@Result(column = "password", property = "user.password"),
@Result(column = "birthday", property = "user.birthday"),
})
public List<Order> findAll();
}
配置方式2:
package com.itcast.mapper;
import com.itcast.domain.Order;
import com.itcast.domain.User;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface OrderMapper {
@Select("SELECT * FROM orders")
@Results({
@Result(column = "oid", property = "id"),
@Result(column = "ordertime", property = "ordertime"),
@Result(column = "total", property = "total"),
@Result(
property = "user",
column = "uid",
javaType = User.class,
one = @One(select = "com.itcast.mapper.UserMapper.findById")
)
})
public List<Order> findAll();
}
(2)程序演示:
package com.itcast.domain;
import java.sql.Timestamp;
import java.util.Date;
public class Order {
private int id;
private Timestamp ordertime;
private double total;
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getOrdertime() {
return ordertime;
}
public void setOrdertime(Timestamp ordertime) {
this.ordertime = ordertime;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", ordertime=" + ordertime +
", total=" + total +
", user=" + user +
'}';
}
}
package com.itcast.domain;
import java.util.Date;
public class User {
private int id;
private String username;
private String password;
private Date birthday;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
'}';
}
}
package com.itcast.mapper;
import com.itcast.domain.Order;
import com.itcast.domain.User;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface OrderMapper {
@Select("SELECT * FROM orders")
@Results({
@Result(column = "oid", property = "id"),
@Result(column = "ordertime", property = "ordertime"),
@Result(column = "total", property = "total"),
@Result(
property = "user",
column = "uid",
javaType = User.class,
one = @One(select = "com.itcast.mapper.UserMapper.findById")
)
})
public List<Order> findAll();
}
<?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>
<typeAliases>
<typeAlias type="com.itcast.domain.User" alias="user"></typeAlias>
</typeAliases>
<typeHandlers>
<typeHandler handler="com.itcast.handler.DateTypeHandler"></typeHandler>
</typeHandlers>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="20001201"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.itcast.mapper"/>
</mappers>
</configuration>
package com.itcast.test;
import com.itcast.domain.Order;
import com.itcast.mapper.OrderMapper;
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.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest2 {
private OrderMapper mapper;
@Before
public void before() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
mapper = sqlSession.getMapper(OrderMapper.class);
}
@Test
public void testFindAll() {
List<Order> orderList = mapper.findAll();
for (Order order : orderList) {
System.out.println(order);
}
}
}
2.1vN查询
用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户。
一对多查询的需求:查询一个用户,与此同时查询出该用户具有的订单。
select * from user;
select * from orders where uid = 查询出用户的id;
(1)配置方式:
package com.itcast.mapper;
import com.itcast.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(column = "id", property = "id"),
@Result(column = "username", property = "username"),
@Result(column = "password", property = "password"),
@Result(
property = "orderList",
column = "id",
javaType = List.class,
many = @Many(select = "com.itcast.mapper.OrderMapper.findByUid")
)
})
public List<User> findUserAndOrderAll();
}
package com.itcast.mapper;
import com.itcast.domain.Order;
import com.itcast.domain.User;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.omg.CORBA.PUBLIC_MEMBER;
import java.util.List;
public interface OrderMapper {
@Select("select * from orders where uid = #{uid}")
public List<Order> findByUid(int uid);
}
(2)程序演示:
package com.itcast.domain;
import java.sql.Timestamp;
import java.util.Date;
public class Order {
private int id;
private Timestamp ordertime;
private double total;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getOrdertime() {
return ordertime;
}
public void setOrdertime(Timestamp ordertime) {
this.ordertime = ordertime;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", ordertime=" + ordertime +
", total=" + total +
", user=" + user +
'}';
}
}
package com.itcast.domain;
import java.util.Date;
import java.util.List;
public class User {
private int id;
private String username;
private String password;
private Date birthday;
private List<Order> orderList;
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
", orderList=" + orderList +
'}';
}
}
package com.itcast.mapper;
import com.itcast.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(column = "id", property = "id"),
@Result(column = "username", property = "username"),
@Result(column = "password", property = "password"),
@Result(
property = "orderList",
column = "id",
javaType = List.class,
many = @Many(select = "com.itcast.mapper.OrderMapper.findByUid")
)
})
public List<User> findUserAndOrderAll();
}
package com.itcast.mapper;
import com.itcast.domain.Order;
import com.itcast.domain.User;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.omg.CORBA.PUBLIC_MEMBER;
import java.util.List;
public interface OrderMapper {
@Select("select * from orders where uid = #{uid}")
public List<Order> findByUid(int uid);
}
<?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>
<typeAliases>
<typeAlias type="com.itcast.domain.User" alias="user"></typeAlias>
</typeAliases>
<typeHandlers>
<typeHandler handler="com.itcast.handler.DateTypeHandler"></typeHandler>
</typeHandlers>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="20001201"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.itcast.mapper"/>
</mappers>
</configuration>
package com.itcast.test;
import com.itcast.domain.User;
import com.itcast.mapper.UserMapper;
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.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest3 {
private UserMapper mapper;
@Before
public void before() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
mapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void testFindAll() {
List<User> orderList = mapper.findUserAndOrderAll();
for (User user : orderList) {
System.out.println(user);
}
}
}
3.NvN查询
用户表和角色表的关系为,一个用户有多个角色,一个角色被多个用户使用。
多对多查询的需求:查询用户同时查询出该用户的所有角色。
select * from user;
select * from role r, user_role ur where r.id = ur.role_id and ur.user_id = 用户的id
(1)配置方式:
package com.itcast.mapper;
import com.itcast.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(column = "id", property = "id"),
@Result(column = "username", property = "username"),
@Result(column = "password", property = "password"),
@Result(
property = "roleList",
column = "id",
javaType = List.class,
many = @Many(select = "com.itcast.mapper.RoleMapper.findByUid")
)
})
public List<User> findUserAndRoleAll();
}
package com.itcast.mapper;
import com.itcast.domain.Role;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface RoleMapper {
@Select("select * from role r, user_role ur where r.id = ur.role_id and ur.user_id = #{uid}")
public List<Role> findByUid(int uid);
}
(2)程序演示:
package com.itcast.domain;
import java.util.Date;
import java.util.List;
public class User {
private int id;
private String username;
private String password;
private Date birthday;
private List<Role> roleList;
public List<Role> getRoleList() {
return roleList;
}
public void setRoleList(List<Role> roleList) {
this.roleList = roleList;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
", roleList=" + roleList +
'}';
}
}
package com.itcast.domain;
public class Role {
private int id;
private String roleName;
private String roleDesc;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
'}';
}
}
package com.itcast.mapper;
import com.itcast.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(column = "id", property = "id"),
@Result(column = "username", property = "username"),
@Result(column = "password", property = "password"),
@Result(
property = "roleList",
column = "id",
javaType = List.class,
many = @Many(select = "com.itcast.mapper.RoleMapper.findByUid")
)
})
public List<User> findUserAndRoleAll();
}
package com.itcast.mapper;
import com.itcast.domain.Role;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface RoleMapper {
@Select("select * from role r, user_role ur where r.id = ur.role_id and ur.user_id = #{uid}")
public List<Role> findByUid(int uid);
}
<?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>
<typeAliases>
<typeAlias type="com.itcast.domain.User" alias="user"></typeAlias>
</typeAliases>
<typeHandlers>
<typeHandler handler="com.itcast.handler.DateTypeHandler"></typeHandler>
</typeHandlers>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="20001201"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.itcast.mapper"/>
</mappers>
</configuration>
package com.itcast.test;
import com.itcast.domain.User;
import com.itcast.mapper.UserMapper;
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.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisTest4 {
private UserMapper mapper;
@Before
public void before() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
mapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void testfindAll() {
List<User> userAndRoleAll = mapper.findUserAndRoleAll();
for (User user : userAndRoleAll) {
System.out.println(user);
}
}
}
|