配置文件驱动
sqlSessionFactory = new SqlSessionFactoryBuilder().build(配置文件字节流) : 获取一个数据库链接的工厂对象
SqlSession sqlSession = sqlSessionFactory.openSession() : 获取数据库链接对象
sqlSession.getMapper(Dao.class) : 获取数据库操作对象
Demo:
sql语句:
CREATE DATABASE Demo;
USE Demo;
CREATE TABLE Demo(
id int PRIMARY KEY,
test1 varchar(10),
test2 int
);
INSERT INTO Demo(id, test1, test2) VALUES (1, "第一个数据", 123);
INSERT INTO Demo(id, test1, test2) VALUES (2, "第二个数据", 234);
INSERT INTO Demo(id, test1, test2) VALUES (3, "第三个数据", 345);
INSERT INTO Demo(id, test1, test2) VALUES (4, "第四个数据", 456);
数据库配置:
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo
jdbc.username=root
jdbc.password=你的密码
核心配置;
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"> <!-- 导入DTD约束 -->
<configuration>
<properties resource="jdbc.properties"/> <!-- 声明一个.properties配置文件,可以用el表达式获取数据 -->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 开启下划线对应驼峰命名规则 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<typeAliases>
<package name="cn.yang.dao"/> <!-- 起别名,别名即文件名 -->
</typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"/> <!-- 声明一个插件(分页插件) -->
</plugins>
<environments default="mysql"> <!-- 声明数据库,可以有多个,default指定使用哪个 -->
<environment id="mysql"> <!-- 配置数据库 -->
<transactionManager type="JDBC"/> <!-- 事务管理(JDBC:默认) -->
<dataSource type="POOLED"> <!-- 开启线程池(UNPOOLED:关闭) -->
<property name="driver" value="${jdbc.driverClassName}"/> <!-- 获取数据库连接的配置信息 -->
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="cn.yang.dao"/> <!-- 关联映射配置(使用package标签须保证映射配置与文件同名,并在同一包下) -->
</mappers>
</configuration>
映射配置:
文件名与类名相同并且与类在同一包下
cn/yang/dao/DemoDao.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="cn.yang.dao.DemoDao"> <!-- 根标签,关联Dao全类名 -->
<resultMap id="BaseResultMap" type="cn.yang.domain.Demo">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="test1" jdbcType="VARCHAR" property="test1"/>
<result column="test2" jdbcType="VARCHAR" property="test2"/>
</resultMap>
<insert id="insertDemoDao" parameterType="cn.yang.domain.Demo"> <!-- id需对应方法名 -->
insert into Demo
values (#{id}, #{test1}, #{test2}) <!-- sql语句,#{变量名} -->
</insert>
<delete id="deleteDemoDao" parameterType="int"> <!-- parameterType:参数值类型 -->
delete
from Demo
where id = #{id}
</delete>
<update id="updateDemoDao" parameterType="cn.yang.domain.Demo">
update Demo
set test1 = #{test1},
test2 = #{test2}
where id = #{id}
</update>
<select id="selectDemoDaoId" resultMap="BaseResultMap" parameterType="int">
select *
from Demo
where id = #{id}
</select>
<select id="selectDemoDao" resultMap="BaseResultMap"> <!-- resultType:返回值类型 -->
select *
from Demo
<!-- 可以使用<if test=“false/true”><foreach collection="参数容器类型(list:集合,array:数组)" open="开头" close="结尾" item="参数变量名" separator="间隔">进行条件判断或循环 -->
</select>
</mapper>
domain:
package cn.yang.domain;
public class Demo {
private int id;
private String test1;
private int test2;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTest1() {
return test1;
}
public void setTest1(String test1) {
this.test1 = test1;
}
public int getTest2() {
return test2;
}
public void setTest2(int test2) {
this.test2 = test2;
}
@Override
public String toString() {
return "Demo{" +
"id=" + id +
", test1='" + test1 + '\'' +
", test2=" + test2 +
'}';
}
}
dao:
package cn.yang.dao;
import cn.yang.domain.Demo;
import java.util.List;
public interface DemoDao {
Integer insertDemo(Demo s);
Integer deleteDemo(int s);
Integer updateDemo(Demo s);
Demo selectDemoId(int s);
List<Demo> selectDemo();
}
factory:
package cn.yang.factory;
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;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MapperFactory {
private MapperFactory() {
}
private static SqlSessionFactory sqlSessionFactory;
static {
try {
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
public static <T> T getMapper(Class<T> aClass) {
return (T) Proxy.newProxyInstance(aClass.getClassLoader(), new Class[]{aClass}, (Object proxy, Method method, Object[] args) -> {
SqlSession sqlSession = getSqlSession();
T mapper = sqlSession.getMapper(aClass);
Object result = method.invoke(mapper, args);
sqlSession.commit();
sqlSession.close();
return result;
});
}
}
service:
package cn.yang.service;
import cn.yang.dao.DemoDao;
import cn.yang.domain.Demo;
import cn.yang.factory.MapperFactory;
import java.util.List;
public class DemoService {
public static void main(String[] args) {
DemoDao mapper = MapperFactory.getMapper(DemoDao.class);
List<Demo> demoDaos1 = mapper.selectDemo();
System.out.println(demoDaos1);
System.out.println("============================");
Demo demo = new Demo();
demo.setId(5);
demo.setTest1("第五个数据");
demo.setTest22(567);
mapper.insertDemo(demo);
demo.setId(3);
demo.setTest1("被改过的第三个数据");
demo.setTest2(321);
mapper.updateDemo(demo);
mapper.deleteDemo(1);
List<Demo> demoDaos2 = mapper.selectDemo();
System.out.println(demoDaos2);
}
}
运行结果:
[Demo{id=1, test1=‘第一个数据’, test2=123}, Demo{id=2, test1=‘第二个数据’, test2=234}, Demo{id=3, test1=‘第三个数据’, test2=345}, Demo{id=4, test1=‘第四个数据’, test2=456}]
============================
[Demo{id=2, test1=‘第二个数据’, test2=234}, Demo{id=3, test1=‘被改过的第三个数据’, test2=321}, Demo{id=4, test1=‘第四个数据’, test2=456}, Demo{id=5, test1=‘第五个数据’, test2=567}]
注解驱动
常用注解:
@Insert("sql语句") //增
@delete("sql语句") //删
@update("sql语句") //改
@select("sql语句") //查
@Results({ //多表
@Result(column = "sid", property = "sid"), //column:获取到的变量名,property:赋值对象的变量名
@Result(column = "name", property = "name"),
@Result(column = "age", property = "age"),
@Result(column = "tid", property = "teacher", javaType = Teacher.class, one = @One(select = "cn.yang.dao.TeacherDao.selectId"))}) //javaType:赋值对象的class对象,one:关联赋值给对象的方法 / 一对多:many = @many()
Demo:
将映射配置 DemoDao.xml 删除
dao改为:
package cn.yang.dao;
import cn.yang.domain.Demo;
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 DemoDao {
@Insert("insert into Demo values (#{id}, #{test1}, #{test2})")
void insertDemo(Demo s);
@Delete("delete from Demo where id = #{id}")
void deleteDemo(int s);
@Update("update Demo set test1 = #{test1}, test2 = #{test2} where id = #{id}")
void updateDemo(Demo s);
@Select("select * from Demo where id = #{id}")
Demo selectDemoId(int s);
@Select("select * from Demo")
List<Demo> selectDemo();
}
service:
package cn.yang.service;
import cn.yang.dao.DemoDao;
import cn.yang.domain.Demo;
import cn.yang.factory.MapperFactory;
import java.util.List;
public class DemoService {
public static void main(String[] args) {
DemoDao mapper = MapperFactory.getMapper(DemoDao.class);
List<Demo> demoDaos1 = mapper.selectDemo();
System.out.println(demoDaos1);
System.out.println("============================");
Demo demo = new Demo();
demo.setId(1);
demo.setTest1("第六个数据");
demo.setTest2(678);
mapper.insertDemo(demo);
demo.setId(5);
demo.setTest1("被改过的第五个数据");
demo.setTest2(543);
mapper.updateDemo(demo);
mapper.deleteDemo(4);
List<Demo> demoDaos2 = mapper.selectDemo();
System.out.println(demoDaos2);
}
}
运行结果:
[Demo{id=2, test1=‘第二个数据’, test2=234}, Demo{id=3, test1=‘被改过的第三个数据’, test2=321}, Demo{id=4, test1=‘第四个数据’, test2=456}, Demo{id=5, test1=‘第五个数据’, test2=567}]
============================
[Demo{id=1, test1=‘第六个数据’, test2=678}, Demo{id=2, test1=‘第二个数据’, test2=234}, Demo{id=3, test1=‘被改过的第三个数据’, test2=321}, Demo{id=5, test1=‘被改过的第五个数据’, test2=543}]