代码结构
image.png
其中mybatis-config.xml是配置文件,sql.properties是配置文件,
FileLyMapper.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要和Mapper所在包+类名保持一致-->
<mapper namespace="com.ly4.com.mapper.FileLyMapper">
<select id="getFile" resultType="com.ly4.com.entity.FileLy">
SELECT * FROM file_ly
</select>
<!--简单的mapper映射-->
<insert id="insert" parameterType="com.ly4.com.entity.FileLy" useGeneratedKeys="true">
<!--order 代表[设置entity的id]是在[执行insert语句] 之前还是之后-->
<selectKey resultType="string" keyProperty="id" order="BEFORE" >
select uuid()
</selectKey>
insert into file_ly(id,name,size,update_time) values(#{id},#{name},#{size},#{updateTime})
</insert>
</mapper>
FileLyMapper.java类
package com.ly4.com.mapper;
import com.ly4.com.builder.FileLyBuilder;
import com.ly4.com.entity.FileLy;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.SelectKey;
public interface FileLyMapper {
/**
* 简单的注解
* @param fileLy
* @return
*/
int insert(FileLy fileLy);
/**
* 直接在方法上的注解
* @param fileLy
* @return
*/
@Insert("insert into file_ly(id,name,size,update_time) values(#{id},#{name},#{size},#{updateTime})")
@SelectKey(statement = "select uuid()",keyColumn = "id",keyProperty = "id",before = true,resultType = String.class)
int insertFileLy(FileLy fileLy);
/**
* 使用provider的注解
* @param fileLy
* @return
*/
@SelectKey(statement = "select uuid()",keyColumn = "id",keyProperty = "id",before = true,resultType = String.class)
@InsertProvider(type = FileLyBuilder.class,method = "buildInsertFileLy")
int insertFileLyWithProvider(FileLy fileLy);
}
buidler类
public class FileLyBuilder {
public static String buildInsertFileLy(FileLy fileLy) {
return new SQL() {{
INSERT_INTO("file_ly");
VALUES("id","'"+fileLy.getId()+"'");
VALUES("name", "'"+fileLy.getName()+"'");
VALUES("size", "'"+fileLy.getSize() +"'");
//这里直接用getUpdateTime会报错,日期格式对不上
VALUES("update_time", "#{updateTime}");
}}.toString();
}
}
测试代码如下
private static void insertFileLy() throws IOException{
InputStream inputStream=Resources.getResourceAsStream("mappings4/mybatis-config.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
try(SqlSession sqlSession=sqlSessionFactory.openSession()){
final FileLyMapper mapper = sqlSession.getMapper(FileLyMapper.class);
mapper.insert(new FileLy("file_name_1",20,new Date()));
mapper.insertFileLy(new FileLy("file_name2",33,new Date()));
mapper.insertFileLyWithProvider(new FileLy("file_name3",33,new Date()));
sqlSession.commit();
}
}
网友评论