一,初识mybatis
1.声明对应表的实体类
package com.mybatis.bean;
public
class Student {
private String id;
private String name;
private int age;
public Student(String id,String name,int age){
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2.声明映射文件表StudentMapper.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=
"studentNameSpace">
<!-- resultMap:表示实体类与映射表
type:实体类全路徑名
id:为实体类与表的映射取一个唯一的编码
-->
<resultMap type=
"com.mybatis.bean.Student" id=
"studentMap">
<!-- id标签:映射主键属性
property:实体类的属性名
column:表的字段名
-->
<id property=
"id" column=
"id"/>
<!-- result标签:映射非主键的属性 -->
<result property=
"name" column=
"name"/>
<result property=
"age" column=
"age"/>
</resultMap>
<!-- 插入语句
parameterType:参数类型
-->
<insert id=
"add" parameterType=
"com.mybatis.bean.Student">
insert into student(id,name,age) values(
</insert>
</mapper>
3.Dao文件
public
class StudentDao {
public void add(Student student){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
sqlSession.insert("studentNameSpace.add",student);
sqlSession.commit();
}
}
4.MyBatisUtil文件
public
class MyBatisUtil {
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
private static SqlSessionFactory sqlSessionFactory;
/**
* 加载位于src/mybatis.xml配置文件
*/
static{
try {
Reader reader = Resources.getResourceAsReader("mybatis.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 禁止外界通过new方法创建
*/
private MyBatisUtil(){}
/**
* 获取SqlSession
*/
public static SqlSession getSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象为空
if(sqlSession == null){
//在SqlSessionFactory非空的情况下,获取SqlSession对象
sqlSession = sqlSessionFactory.openSession();
//将SqlSession对象与当前线程绑定在一起
threadLocal.set(sqlSession);
}
//返回SqlSession对象
return sqlSession;
}
/**
* 关闭SqlSession与当前线程分开
*/
public static void closeSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象非空
if(sqlSession != null){
//关闭SqlSession对象
sqlSession.close();
//分开当前线程与SqlSession对象的关系,目的是让GC尽早回收
threadLocal.remove();
}
}
}
5.配置mabatis连接数据库的文件
<?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>
<environments default=
"mysql_development">
<environment id=
"mysql_development">
<transactionManager type=
"JDBC"/>
<dataSource type=
"POOLED">
<property name=
"driver" value=
"com.mysql.jdbc.Driver"/>
<property name=
"url" value=
"jdbc:mysql://127.0.0.1:3306/mydb4"/>
<property name=
"username" value=
"root"/>
<property name=
"password" value=
"123"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource=
"com/mybatis/bean/StudentMapper.xml"></mapper>
</mappers>
</configuration>
6.测试
public static void main(String[] args) {
//测试数据库配置文件是否正确
Connection conn = MyBatisUtil.getSqlSession().getConnection();
System.out.println(conn!=null?
"连接成功":
"连接失败");
//测试插入一条数据
StudentDao dao = new StudentDao();
dao.add(new Student(
"0001",
"daMing",
20));
}
二,myBatist的增删改查
1.studentMapper.xml文件的配置
<!-- 插入语句
parameterType:参数类型
-->
<insert id=
"add" parameterType=
"com.mybatis.bean.Student">
insert into student(id,name,age) values(
</insert>
<!--
resultMap:解决bean类和表字段不一致导致的映射问题
-->
<select id=
"add" parameterType=
"int" resultMap=
"studentMap">
select s_id,s_name,s_age
from student where s_id =
</select>
<!--查询语句
parameterType:请求参数类型
resultType:返回值类型
-->
<select id=
"findById" parameterType=
"string" resultType=
"com.mybatis.bean.Student">
select id,name,age
from student where id =
</select>
<!-- 查询所有
如果返回结果为list,那么resultType只需要写list里面的类型
-->
<select id=
"findAll" resultType=
"com.mybatis.bean.Student">
select id,name,age
from student;
</select>
<!-- 更新操作 -->
<update id=
"update" parameterType=
"com.mybatis.bean.Student">
update student set age =
</update>
<!--删除-->
<delete id=
"deleteById" parameterType=
"string">
delete
from student where id =
</delete>
<!-- 多参数查询
map:封装多个查询参数
-->
<select id=
"findByLimit" parameterType=
"map" resultMap=
"studentMap">
select id,name,age
from student limit
</select>
2.dao文件
//添加学生
public void add(Student student){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
sqlSession.insert(
"studentNameSpace.add",student);
sqlSession.commit();
}
//根据id查询学生
public Student findById(String id){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
try {
Student student = sqlSession.selectOne(
"studentNameSpace.findById",id);
sqlSession.commit();
return student;
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
sqlSession.rollback();
}
finally{
MyBatisUtil.closeSqlSession();
}
return null;
}
//查询多个学生
public List<Student> findAll(){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
try {
List<Student> students = sqlSession.selectList(
"studentNameSpace.findAll");
sqlSession.commit();
return students;
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
sqlSession.rollback();
}
finally{
MyBatisUtil.closeSqlSession();
}
return null;
}
//更新学生
public void update(Student student){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
try {
sqlSession.update(
"studentNameSpace.update",student);
sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
sqlSession.rollback();
}
finally{
MyBatisUtil.closeSqlSession();
}
}
//删除学生
public void deleteById(String id){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
try {
sqlSession.delete(
"studentNameSpace.deleteById",id);
sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
sqlSession.rollback();
}
finally{
MyBatisUtil.closeSqlSession();
}
}
//分页查询
public List<Student> findByLimit(int start,int size){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
try {
Map<String,Integer> map = new HashMap<String, Integer>();
map.put(
"start", start);
map.put(
"size", size);
List<Student> students = sqlSession.selectList(
"studentNameSpace.findByLimit",map);
sqlSession.commit();
return students;
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
sqlSession.rollback();
}
finally{
MyBatisUtil.closeSqlSession();
}
return null;
}
3.测试
StudentDao dao = new StudentDao();
// dao.add(new Student(
"0002",
"xiaoLong",
10));
// dao.add(new Student(
"0003",
"哈哈",
10));
// dao.add(new Student(
"0004",
"呵呵",
10));
// Student student = dao.findById(
"0001");
// System.out.println(student.getName()+
":"+student.getAge());
/**
List<Student> students = dao.findAll();
for (Student student : students) {
System.out.println(student.getName()+
":"+student.getAge());
}*/
// dao.update(new Student(
"0003",
"hehe",
10));
dao.deleteById(
"0004");