1、常用注解
@Insert:新增
@Update:更新
@Delete:删除
@Select:查询
@Result:结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@One:一对一结果集封装
@Many:一对多结果集封装
2、简单的增删改查
(1)创建项目
?(2)配置pom.xml文件
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
(3)编写实体类和数据库
public class User {
private int id;
private String username;
private String password;
private Date birthday;}
(4)配置核心文件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标签加载外部properties文件-->
<properties resource="jdbc.properties"></properties>
<!--数据源环境-->
<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>
<mapper resource="com/dhh/mapper/UserMapper.xml"/>
</mappers>-->
<!--加载配置关系 使用注解后 TODO-->
<mappers>
<!--指定接口所在的包 -->
<package name="com.dhh.mapper"/>
</mappers>
</configuration>
(5)配置UserMapper.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.dhh.mapper.UserMapper"><!--调用名称 userMapper.findAll-->
<insert id="save" parameterType="user">
insert into user values(#{id},#{username},#{password},#{birthday})
</insert>
<delete id="delete" parameterType="int">
delete from user where id=#{id}
</delete>
<update id="update" parameterType="user">
update user set username=#{username},password=#{password} where id=#{id}
</update>
<select id="findAll" resultType="user">
select * from user
</select>
<select id="findById" parameterType="int" resultMap="user">
select * from user where id=#{id}
</select>
</mapper>
使用注解:直接在UserMapper接口中写入SQL语句
package com.dhh.mapper;
import com.dhh.domain.User;
import org.apache.ibatis.annotations.*;
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();
}
(6)编写测试类
package com.dhh.test;
import com.dhh.domain.User;
import com.dhh.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 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("sisi");
user.setPassword("111");
mapper.save(user);
}
@Test
public void testUpdate(){
User user =new User();
user.setId(5);
user.setUsername("sisi");
user.setPassword("123");
mapper.update(user);
}
@Test
public void testDelete(){
User user =new User();
mapper.delete(17);
}
@Test
public void testFindById(){
User user= mapper.findById(4);
System.out.println(user);
}
@Test
public void testFindAll(){
List<User> all= mapper.findAll();
for (User user:all) {
System.out.println(user);
}
}
}
3、MyBatis的注解实现复杂映射开发
我们可以使用@Result注解、@Results注解、@One注解、@Many注解组合完成复杂关系配置
3.1 一对一?
(1)编写实体类和数据库
public class Order {
private int id;
private Date ordertime; //下单时间
private double total; //总金额
private User user; //当前订单属于哪一个用户
}
?(2)使用注解:直接在OrderMapper.xml接口中写入SQL语句
package com.dhh.mapper;
import com.dhh.domain.Order;
import com.dhh.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 where uid=#{uid}")
public List<Order> findByUid(int uid);
/* 一对一查询方式一
@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")
})
public List<Order> findAll();
*/
//一对一查询方式二
@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",//根据哪个字段去查询user表的数据
javaType = User.class,//要封装的实体类型
//select属性,代表查询的哪个接口的方法获得数据
one=@One(select = "com.dhh.mapper.UserMapper.findById")
)
})
public List<Order> findAll();
}
(3)测试代码
package com.dhh.test;
import com.dhh.domain.Order;
import com.dhh.domain.User;
import com.dhh.mapper.OrderMapper;
import com.dhh.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 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 testSave(){
List<Order> all = mapper.findAll();
for(Order order : all){
System.out.println(all);
}
}
}
3.2 一对多
(1)创建实体类
public class User {
private int id;
private String username;
private String password;
private Date birthday;
//当前用户具有的订单
private List<Order> orderList;
}
(2)在UserMapper接口中添加如下代码:
@Select("select * from user") //一对多
@Results({
@Result(id = true, 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.dhh.mapper.OrderMapper.findByUid")
)
})
public List<User> findUserAndOrderAll();
使用OrderMapper接口中的方法(子查询)
(4)测试
package com.dhh.test;
import com.dhh.domain.Order;
import com.dhh.domain.User;
import com.dhh.mapper.OrderMapper;
import com.dhh.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 testSave(){
List<User> userAndOrderAll= mapper.findUserAndOrderAll();
for (User user:userAndOrderAll) {
System.out.println(user);
}
}
}
3.3 多对多
(1)创建实体类
public class Role {
private int id;
private String roleName;
private String roleDesc;
}
在User实体类中追加属性:
//当前用户具备哪些角色
private List<Role> roleList;
(2)新建RoleMapper接口,编写role方法(子查询使用)
public interface RoleMapper {
@Select("select * from sys_user_role ur,sys_role r where ur.roleId=r.id and ur.userId=#{uid}")
public List<Role> findByUid(int uid);
}
(3)在UserMapper接口中添加如下代码:
@Select("select * from user") //多对多
@Results({
@Result(id = true,column = "id",property = "id"),
@Result(id = true,column = "username",property = "username"),
@Result(id = true,column = "password",property = "password"),
@Result(
property = "roleList",
column = "id",
javaType = List.class,
many = @Many(select = "com.dhh.mapper.RoleMapper.findByUid")
)
})
public List<User> findUserAndRoleAll();
(4)测试
package com.dhh.test;
import com.dhh.domain.User;
import com.dhh.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 testSave(){
List<User> userAndRoleAll= mapper.findUserAndRoleAll();
for (User user:userAndRoleAll) {
System.out.println(user);
}
}
}
总结:坚持很难,放弃容易,再接再厉,一起进步!
|