利用注解简化配置
1.常用的注解
注解可以替代掉原有的XML的各种标签,在程序中利用注解进行开发, 简化程序的配置过程。
注解 | 对应XML | 说明 |
---|---|---|
@Insert | <insert> | 新增SQL |
@Update | <update> | 更新SQL |
@Delet | <delete> | 删除SQL |
@Select | <select> | 查询SQL |
@Param | – | 参数映射 |
@Results | <resultMap> | 结果映射 |
@Result | <id><result> | 字段映射 |
2. 注解之查询
使用注解时,是不需要些mapper这个xm文件的,取而代之的是需要创建一个名为dao的包, 在这个包中创建一系列的接口,利用接口和注解,替代原有的xml文件。
DAO接口
public interface GoodsDAO {
@Select("select * from t_goods where current_price between #{min} and #{max} order by current_price limit 0, #{limit}")
public List<Goods> selectByPriceRange(@Param("min") Float min,@Param("max") Float max, @Param("limit") Integer limit);
}
测试
@Test
/**
*
*/
public void testSelectByPriceRange() throws Exception {
SqlSession session = null;
try{
session = MyBatisUtils.openSession();
GoodsDAO goodsDAO = session.getMapper(GoodsDAO.class);
List <Goods> list = goodsDAO.selectByPriceRange(100f, 200f, 3);
System.out.println(list.size());
}catch(Exception e){
if(session != null){
session.rollback();
}
throw e;
}finally{
MyBatisUtils.closeSession(session);
}
}
mybatis-config.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"
>
<configuration>
<settings>
<!--goods_id ==> goodsId 驼峰命名转换-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
<property name="reasonable" value="true"/>
</plugin>
</plugins>
<!-- 允许有多个environment ,通过default进行环境的修改,设置默认指向的数据库 -->
<environments default="dev">
<!-- 配置环境, 不同的环境不同的id名字 -->
<environment id="dev">
<!-- 采用JDBC方式对数据库事物进行commit / roolback -->
<transactionManager type="JDBC"></transactionManager>
<!-- 采用MyBatis内置连接池的方式管理数据库连接 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/king?sueUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
<!--C3P0连接池的设置-->
<!-- <dataSource type="com.mybatis.datasource.C3P0DataSourceFactory">-->
<!-- <property name="driverClass" value="com.mysql.jdbc.Driver"/>-->
<!-- <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/king?sueUnicode=true&characterEncoding=UTF-8"/>-->
<!-- <property name="user" value="root"/>-->
<!-- <property name="password" value="root"/>-->
<!-- <property name="initialPoolSize" value="5"/>-->
<!-- <property name="maxPoolSize" value="20"/>-->
<!-- <property name="minPoolSize" value="5"/>-->
<!-- </dataSource>-->
</environment>
</environments>
<mappers>
<!-- <mapper class="com.mybatis.dao.GoodsDAO"/>-->
<package name="com.mybatis.dao"/>
</mappers>
</configuration>
3. 注解之新增
@Insert("insert t_goods(title, sub_title, original_cost, current_price, discount, is_free_delivery, category_Id)\n" +
" values(#{title}, #{subTitle}, #{originalCost}, #{currentPrice}, #{discount}, #{isFreeDelivery}, #{categoryId})")
@SelectKey(statement = "select last_insert_id()", before = false, keyProperty = "goodsId", resultType = Integer.class)
public int insert(Goods goods);
测试
@Test
/**
*跟新数据
*/
public void testInsert() throws Exception {
SqlSession session = null;
try{
session = MyBatisUtils.openSession();
GoodsDAO goodsDAO = session.getMapper(GoodsDAO.class);
Goods goods = new Goods();
goods.setTitle("测试商品");
goods.setSubTitle("测试子标题");
goods.setOriginalCost(300f);
goods.setCurrentPrice(150f);
goods.setDiscount(0.5f);
goods.setIsFreeDelivery(1);
goods.setCategoryId(43);
int num = goodsDAO.insert(goods);
System.out.println(num);
System.out.println(goods.getGoodsId());
session.commit();
}catch(Exception e){
if(session != null){
session.rollback();
}
throw e;
}finally{
MyBatisUtils.closeSession(session);
}
}
4.注解之查询整个表
goodsDOT类
package com.mybatis.dto;
// Data Transfer Object 数据传输对象
public class GoodsDTO {
private Integer goodsId; //商品编号
private String title; // 标题
private Float currentPrice; // 当前价格
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
public void setTitle(String title) {
this.title = title;
}
public void setCurrentPrice(Float currentPrice) {
this.currentPrice = currentPrice;
}
public Integer getGoodsId() {
return goodsId;
}
public String getTitle() {
return title;
}
public Float getCurrentPrice() {
return currentPrice;
}
}
接口
@Select("select * from t_goods")
//results相当于resultMap
@Results({
// <id>
@Result(column="goods_Id", property = "goodsId", id = true),
// result
@Result(column="title", property = "title"),
@Result(column = "current_price", property = "currentPrice")
})
public List<GoodsDTO> selectAll();
测试
@Test
/**
* 测试获取所有数据
*/
public void testSelectAll() throws Exception {
SqlSession session = null;
try{
session = MyBatisUtils.openSession();
GoodsDAO goodsDAO = session.getMapper(GoodsDAO.class);
List<GoodsDTO> list= goodsDAO.selectAll();
for (GoodsDTO g : list){
System.out.println(g.getTitle() + g.getCurrentPrice());
}
}catch(Exception e){
if(session != null){
session.rollback();
}
throw e;
}finally{
MyBatisUtils.closeSession(session);
}
}