Mybatis学习
文章目录
基本方式
一、实体类
准备一个实体类,映射数据库里的一张表
二、配置mybatis-config.xml
配置文件mybatis-config.xml 作用主要是提供连接数据库用的驱动,数据库名称,编码方式,账号密码 ,idea里需要自己配一个settings->Editor->file and code Templates放上模板
<?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=""></properties>
<typeAliases>
<package name="com.nhjia.pojo"/>
/*在该包中扫描配置*/
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
/*提供连接数据库用的驱动,数据库名称,编码方式,账号密码 */
<mappers>
<mapper resource="com/nhjia/pojo/Category.xml"></mapper>
<mapper resource="com/nhjia/pojo/Product.xml"></mapper>
<mapper resource="com/nhjia/pojo/Order.xml"></mapper>
<mapper resource="com/nhjia/pojo/OrderItem.xml">
</mapper>
/*映射文件*/
</mappers>
</configuration>
三、配置mybatis-mapper.xml(实体类映射配置文件)
配置实体类的xml文件,实现CRUD操作;
<?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.nhjia.pojo">
/*命名空间*/
<insert id="addCategory" parameterType="Category" >
insert into category_ ( name ) values (#{name})
</insert>
/*id用于标识用于后面使用*/
/*parameterType为输入参数*/
/*resultType返回类型,且列名与实体类列名一致*/
<delete id="deleteCategory" parameterType="Category" >
delete from category_ where id= #{id}
</delete>
<select id="getCategory" parameterType="_int" resultType="Category">
select * from category_ where id= #{id}
</select>
<update id="updateCategory" parameterType="Category" >
update category_ set name=#{name} where id=#{id}
</update>
<select id="listCategory" resultType="Category">
select * from category_
</select>
</mapper>
四、最后实际使用
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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 com.nhjia.pojo.Category;
public class TestMybatis {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=sqlSessionFactory.openSession();
/*根据配置文件mybatis-config.xml得到sqlSessionFactory */
/*SqlSessionFactory 的实例可以获得操作数据的SqlSession实例,通过这个实例对数据库进行操作*/
Category c = new Category();
c.setName("新增加的Category");
session.insert("addCategory",c);
listAll(session);
session.commit();
/*事务操作,如果有多个操作其中一个出错,全部不执行*/
session.close();
}
private static void listAll(SqlSession session) {
List<Category> cs = session.selectList("listCategory");
for (Category c : cs) {
System.out.println(c.getName());
}
}
}
一对多,多对一,多对多
一、一对多
修改对应的mapper.xml,修改内容
<!-- resultMap用于sql列名与实体类列名不一致情况,column是sql列名,property是实体类列名-->
<resultMap type="Category" id="categoryBean">
<id column="cid" property="id" />
<result column="cname" property="name" />
<!-- 一对多的关系 -->
<!-- collection即JavaBean内部嵌套一个复杂数据类型(集合)。和使用association元素一样-->
<!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
<collection property="products" ofType="Product">
<id column="pid" property="id" />
<result column="pname" property="name" />
<result column="price" property="price" />
</collection>
</resultMap>
<!-- category_ 表左外连接于product_表-->
<!-- 关联查询分类和产品表 -->
<select id="listCategory" resultMap="categoryBean">
select c.*, p.*, c.id 'cid', p.id 'pid', c.name 'cname', p.name 'pname' from category_ c left join product_ p on c.id = p.cid
</select>
resultMap中id和result的区别:
子元素id代表resultMap的主键,而result代表其属性。
在自定义的resultMap中第一列通常是主键id,那么id 和result有什么区别呢?
id和result都是映射单列值到一个属性或字段的简单数据类型。
唯一不同的是,id是作为唯一标识的,当和其他对象实例对比的时候,这个id很有用,尤其是应用到缓存和内嵌的结果映射。
property: 映射数据库列的字段或属性,如果JavaBean的属性与给定的名称匹配,就会使用匹配的名字,否则MyBatis将搜索给定名称的字段,两种情况下你都可以使用逗点的属性形式,比如,你可以映射到“”username:,也可以映射到“address.street.number”
column:数据库的列名或者列标签别名,与传递个resultSet.getString(columnName)的参数名称相同。
二、多对一
修改实体类的mapper.xml
<resultMap type="Product" id="productBean">
<id column="pid" property="id" />
<result column="pname" property="name" />
<result column="price" property="price" />
<!-- 多对一的关系使用association -->
<!-- property: 指的是属性名称, javaType:指的是属性的类型 -->
<association property="category" javaType="Category">
<id column="cid" property="id"/>
<result column="cname" property="name"/>
</association>
</resultMap>
<!-- category_ 表左外连接于product_表-->
<!-- 根据id查询Product, 关联将Orders查询出来 -->
<select id="listProduct" resultMap="productBean">
select c.*, p.*, c.id 'cid', p.id 'pid', c.name 'cname', p.name 'pname' from category_ c left join product_ p on c.id = p.cid
</select>
三、多对多
定义一个中间类b,a类对b类一对多的关系,b类对c类多对一的关系;然后实现
a对c的多对多的关系
修改对应的mapper.xml
<resultMap type="Order" id="orderBean">
<id column="oid" property="id" />
<result column="code" property="code" />
<!-- 一对多-->
<collection property="orderItems" ofType="OrderItem">
<id column="oiid" property="id" />
<result column="number" property="number" /> <!-- 多对一 -->
<association property="product" javaType="Product">
<id column="pid" property="id"/>
<result column="pname" property="name"/>
<result column="price" property="price"/>
</association>
</collection>
</resultMap>
<select id="listOrder" resultMap="orderBean">
select o.*,p.*,oi.*, o.id 'oid', p.id 'pid', oi.id 'oiid', p.name 'pname'
from order_ o
left join order_item_ oi on o.id =oi.oid
left join product_ p on p.id = oi.pid
</select>
<select id="getOrder" resultMap="orderBean">
select o.*,p.*,oi.*, o.id 'oid', p.id 'pid', oi.id 'oiid', p.name 'pname'
from order_ o
left join order_item_ oi on o.id =oi.oid
left join product_ p on p.id = oi.pid
where o.id = #{id}
</select>
动态SQL
if标签
<select id="listProduct" resultType="Product">
select * from product_
<if test="name!=null">
where name like concat('%',#{name},'%')
</if>
<!-- 如果传递过来一个name的参数不为空就运行if里的sql,否则就是外层的sql-->
</select>
where标签
多条件判断时
<select id="listProduct" resultType="Product">
select * from product_
<where>
<if test="name!=null">
and name like concat('%',#{name},'%')
</if>
<if test="price!=null and price!=0">
and price > #{price}
</if>
</where>
</select>
标签会进行自动判断
如果任何条件都不成立,那么就在sql语句里就不会出现where关键字
如果有任何条件成立,会自动去掉多出来的 and 或者 or。
update里有set标签
<update id="updateProduct" parameterType="Product" >
update product_
<set>
<if test="name != null">name=#{name},</if>
<if test="price != null">price=#{price}</if>
</set>
where id=#{id}
</update>
choose标签
<select id="listProduct" resultType="Product">
SELECT * FROM product_
<where>
<choose>
<when test="name != null">
and name like concat('%',#{name},'%')
</when>
<when test="price !=null and price != 0">
and price > #{price}
</when>
<otherwise>
and id >1
</otherwise>
</choose>
</where>
</select>
when和otherwise实现if 和else的功能;
foreach标签
<select id="listProduct" resultType="Product">
SELECT * FROM product_
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
foreach元素的属性包含 item,index,collection,open,separator,close。
item表示集合中每一个元素进行迭代时的别名,非限定词
index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,
open表示该语句以什么开始,这边使用"(",则会在sql进行拼接加上"(", 如where id in (
separator表示在每次进行迭代之间以什么符号作为分隔 符,如如where id in ( 1,
close表示以什么结束,这边使用"(",则会在list遍历后进行拼接加上")",如where id in (1,2)
collection表示要遍历的集合
bind标签
<select id="listProduct" resultType="Product">
<bind name="likename" value="'%' + name + '%'" />
select * from product_ where name like #{likename}
</select>
可以替代like concat(’%’,#{name},’%’);
注解方式
实现
1、修改mapper.xml实体类映射xml为接口
public interface CategoryMapper {
@Insert(" insert into category_ ( name ) values (#{name}) ")
public int add(Category category);
@Delete(" delete from category_ where id= #{id} ")
public void delete(int id);
@Select("select * from category_ where id= #{id} ")
public Category get(int id);
@Update("update category_ set name=#{name} where id=#{id} ")
public int update(Category category);
@Select(" select * from category_ ")
public List<Category> list();
}
2、在mybatis-config.xml里加入映射接口
<mapper class
="com.how2java.mapper.CategoryMapper"
/>
3、实际使用
一对多,多对一,多对多
一对多:
@Results 通过@Result和@Many中调用ProductMapper.listByCategory()方法相结合,来获取一对多关系
public interface CategoryMapper {
@Select(" select * from category_ ")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "products", javaType = List.class, column = "id", many = @Many(select = "com.how2java.mapper.ProductMapper.listByCategory") )
})
public List<Category> list();
}
多对一:
public interface ProductMapper {
@Select(" select * from product_ ")
@Results({
@Result(property="category",column="cid",one=@One(select="com.how2java.mapper.CategoryMapper.get"))
})
public List<Product> list();
}
多对多:
还是一个中间类b,b对c多对一,a对b一对多
套用上面设置a对b的一对多接口,和b对c的多对一接口即可;