添加配置mybatis-config
<?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 resource="db.properties"/>
<typeAliases>
<package name="pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="mapper"/>
</mappers>
</configuration>
连接数据库配置 db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&user=false&serverTimeZoneUTC
username=root
password=123456
开启一个数据库池子的工具类
public class MyBatisUtils {
public static SqlSessionFactory factory;
static {
String resource = "mybatis-config.xml";
try {
InputStream inputStream = Resources.getResourceAsStream(resource);
factory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
添加pojo实体类,对应mapper.xml写sql语句
<?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="">
</mapper>
多对一写法
<select id="getStudent1" resultMap="getAll1">
select *
from test.user,
test.teacher
where test.teacher.tid = test.user.tid
and user.tid = ${id};
</select>
<resultMap id="getAll1" type="User">
<result property="tid" column="tid"/>
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" javaType="Teacher">
<result property="tid" column="tid"/>
<result property="name" column="name"/>
</association>
</resultMap>
一对多写法
<select id="getTeacher" resultMap="map">
select *
from test.user
join teacher t on t.tid = user.tid
where t.tid = #{id}
</select>
<resultMap id="map" type="Teacher">
<collection property="users" ofType="User">
<result property="id" column="id"/>
<result property="name" column="name"/>
</collection>
</resultMap>
各种关键字用法
mapper namespace="mapper.BlogMapper">
<cache/>
<sql id="select">
select *
from test.blog
<where>
<choose>
<when test="id!=null">
id=#{id};
</when>
<when test="title!=null">
title=#{title};
</when>
</choose>
</where>
</sql>
<select id="queryBlogs" resultType="Blog">
<include refid="select"/>
</select>
<update id="updateBlogs">
update test.blog
<set>
<if test="title!=null">
title=#{title},
</if>
</set>
where id=#{id};
</update>
<select id="queryBlog1" resultType="Blog">
select *from test.blog
<where>
<foreach collection="list" item="id" open="(" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>