标签:< select id="" resultType="" >
1.1.1 序号参数绑定
arg0 arg1 arg2 …
param1 param2 param3
package com.dao;
import com.entity.Stu;
public interface StuDao {
//使用原生参数绑定
public Stu getStuByNameAndId(String stuName, int stuId);
}
<select id="getStuByNameAndId" resultType="com.entity.Stu">
select * from t_stu where stuname = #{arg0} and stuid = #{arg1};
</select>
<select id="getStuByNameAndId" resultType="com.entity.Stu">
select * from t_stu where stuname = #{param1} and stuid = #{param2};
</select>
1.1.2 注解参数绑定【推荐】
package com.dao;
import com.entity.Stu;
import org.apache.ibatis.annotations.Param;
public interface StuDao {
public Stu getStuByNameAndId(@Param("stuName") String stuName, @Param("stuId") int stuId);
}
<select id="getStuByNameAndId" resultType="com.entity.Stu">
select * from t_stu where stuname = #{stuName} and stuid = #{stuId};
</select>
1.1.3 Map参数绑定
public List<Stu> getStuByPage(Map<String,Object> map);
<select id="getStuByPage" resultType="Stu">
select * from t_stu limit #{begin},#{end};
</select>
//分页查询
Map<String,Object> map = new HashMap<String, Object>();
int pageNo = 1;
int pageSize = 2;
int begin = (pageNo-1)*pageSize;
map.put("begin",begin);
map.put("end",pageSize);
List<Stu> stuList = sqlSession.getMapper(StuDao.class).getStuByPage(map);
System.out.println(stuList.toString());
1.1.4 模糊查询
public List<Stu> getStuByNameLike(@Param("stuName") String stuName);
<select id="getStuByNameLike" resultType="Stu">
select * from t_stu where stuname like concat('%',#{stuName},'%');
</select>
标签:< delete id="" parameterType="" >
DELETE FROM t_users
WHERE id = #{id}
标签:< update id="" parameterType="" >
UPDATE t_users SET name=#{name}, password=#{password}, sex=#{sex}, birthday=#{birthday}
WHERE id = #{id}
标签:< insert id="" parameterType="" >
INSERT INTO t_users VALUES(#{id},#{name},#{password},#{sex},#{birthday},NULL);
INSERT INTO t_users VALUES(#{id},#{name},#{password},#{sex},#{birthday},NULL);
INSERT INTO t_users VALUES(NULL,#{name},#{password},#{sex},#{birthday},NULL);
标签:< selectKey id="" parameterType="" order="AFTER|BEFORE">
1.5.1 通过last_insert_id()查询主键
create table t_product(
id int primary key auto_increment,
name varchar(50)
)default charset = utf8;
class Product{
private Integer id;
private String name;
//set+get ...
}
SELECT LAST_INSERT_ID()
INSERT INTO t_product(id,name) VALUES(#{id},#{name})
1.5.2 通过uuid()查询主键
create table t_order(
id varchar(32) primary key, # 字符型主键
name varchar(50)
)default charset = utf8;
class Order{
private Integer id;
private String name;
//set+get ...
}
SELECT REPLACE(UUID(),'-','')
INSERT INTO t_order(id,name) VALUES(#{id},#{name})
Resource:用于获得读取配置文件的IO对象,耗费资源,建议通过IO一次性读取所有所需要的数据。
SqlSessionFactory:SqlSession工厂类,内存占用多,耗费资源,建议每个应用只创建一个对象。
SqlSession:相当于Connection,可控制事务,应为线程私有,不被多线程共享。
将获得连接、关闭连接、提交事务、回滚事务、获得接口实现类等方法进行封装。
package com.util;
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 java.io.IOException;
import java.io.InputStream;
public class MyBatisUtil {
//1. 读取配置文件 获取SQLSession对象
//2. 事务的处理
//3. SqlSession 释放
//会话工厂对象
private static SqlSessionFactory factory;
//创建ThreadLocal绑定当前线程中的SqlSession对象
private static final ThreadLocal<SqlSession> SQL_SESSION_THREAD_LOCAL = new ThreadLocal<SqlSession>();
//ThreadLocal 每一个线程中都有一个ThreadLocal类型的成员变量
//每一个Thread中都有一个 ThreadLocal
// get 获取当先线程中维护的内容
// set 设置当前线程维护的内容
//init 获取当线程中内容的初始值
// remove 删除维护的内容
static {
try {
InputStream stream = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(stream);
} catch (IOException e) {
e.printStackTrace();
}
}
//获得连接(从tl中获得当前线程SqlSession)
public static SqlSession getSqlSession(){
SqlSession sqlSession = SQL_SESSION_THREAD_LOCAL.get();
if (sqlSession == null){
sqlSession = factory.openSession();
SQL_SESSION_THREAD_LOCAL.set(sqlSession);
}
return sqlSession;
}
//释放连接(释放当前线程中的SqlSession)
public static void close(){
getSqlSession().close();
SQL_SESSION_THREAD_LOCAL.remove();
}
//提交事务(提交当前线程中的SqlSession所管理的事务)
public static void commit(){
getSqlSession().commit();
close();
}
//回滚事务(回滚当前线程中的SqlSession所管理的事务)
public static void rollback(){
getSqlSession().rollback();
close();
}
//获得接口实现类对象
public static <T> T getMapper(Class<T> t){
return getSqlSession().getMapper(t);
}
}
调用MyBatisUtils中的封装方法。
@Test
public void testUtils() {
try {
UserDao userDao = MyBatisUtils.getMapper(UserDao.class);
userDao.deleteUser(15);
MyBatisUtils.commit();
} catch (Exception e) {
MyBatisUtils.rollback();
e.printStackTrace();
}
}
实体间的关系:关联关系(拥有 has、属于 belong)
一个学生对应一个班级
public Stu getStuAndGrade(Integer stuId);
<resultMap id="stuGrade" type="com.entity.Stu">
<id column="stuid" property="stuId"></id>
<result column="stuname" property="stuName"></result>
<association property="grade" javaType="com.entity.Grade">
<id column="gid" property="gId"></id>
<result column="gname" property="gName"></result>
</association>
</resultMap>
<select id="getStuAndGrade" resultMap="stuGrade">
select * from t_stu , t_grade where t_stu.gradeid = t_grade.gid and t_stu.stuid = #{stuId}
</select>
注意:指定“一方”关系时(对象),使用< association javaType="" >
一个班级里有多名学生
package com.entity;
import java.util.List;
public class Grade {
private int gId;
private String gName;
private List<Stu> stuList;
public List<Stu> getStuList() {
return stuList;
}
public void setStuList(List<Stu> stuList) {
this.stuList = stuList;
}
public Grade() {
}
public Grade(int gId, String gName) {
this.gId = gId;
this.gName = gName;
}
public int getgId() {
return gId;
}
public void setgId(int gId) {
this.gId = gId;
}
public String getgName() {
return gName;
}
public void setgName(String gName) {
this.gName = gName;
}
@Override
public String toString() {
return "Grade{" +
"gId=" + gId +
", gName='" + gName + '\'' +
", stuList=" + stuList +
'}';
}
}
package com.dao;
import com.entity.Grade;
import java.util.List;
public interface GradeDao {
public List<Grade> getGradeAndStu();
}
<?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.dao.GradeDao">
<resultMap id="gradeStu" type="Grade">
<id column="gid" property="gId"></id>
<collection property="stuList" ofType="Stu">
<id column="stuid" property="stuId"></id>
</collection>
</resultMap>
<select id="getGradeAndStu" resultMap="gradeStu">
select * from t_stu,t_grade where t_stu.gradeid = t_grade.gid
</select>
</mapper>
注意:指定“多方”关系时(集合),使用< collection ofType="" >
一个学生可以选修多门课程,一个课程可以有多个学生选修
//Stu.java
private List<Course> courseList;
//StuDao.java
public List<Stu> getStuCourse();
//Course.java
package com.entity;
import java.util.List;
public class Course {
private Integer cId;
private String cName;
private List<Stu> stuList;
public Course() {
}
public Course(Integer cId, String cName, List<Stu> stuList) {
this.cId = cId;
this.cName = cName;
this.stuList = stuList;
}
public Integer getcId() {
return cId;
}
public void setcId(Integer cId) {
this.cId = cId;
}
public String getcName() {
return cName;
}
public void setcName(String cName) {
this.cName = cName;
}
public List<Stu> getStuList() {
return stuList;
}
public void setStuList(List<Stu> stuList) {
this.stuList = stuList;
}
@Override
public String toString() {
return "Course{" +
"cId=" + cId +
", cName='" + cName + '\'' +
", stuList=" + stuList +
'}';
}
}
//StuDaoMapper.xml
<resultMap id="stuCourse" type="Stu">
<id column="stuid" property="stuId"></id>
<collection property="courseList" ofType="com.entity.Course">
<id column="cid" property="cId"></id>
</collection>
</resultMap>
<select id="getStuCourse" resultMap="stuCourse">
select * from t_stu inner join
t_stu_course
on
t_stu.stuid = t_stu_course.sid
inner join
t_course
on
t_stu_course.cid = t_course.cid
</select>
一方,添加集合;多方,添加对象。
双方均可建立关系属性,建立关系属性后,对应的Mapper文件中需使用< ResultMap >完成多表映射。
持有对象关系属性,使用< association property="dept" javaType="department" >
持有集合关系属性,使用< collection property="emps" ofType="employee" >