动态SQL环境搭建
1 环境搭建
1、1 数据库
CREATE TABLE blog(
id VARCHAR(64) NOT NULL ,
title VARCHAR(64) NOT NULL,
author VARCHAR(64) NOT NULL,
create_time DATETIME NOT NULL,
views INT(30) NOT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
1、2实体类 (这里要导入lombok) 工具类
@Data
public class blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
使用UUID生成随机数
public class IDUtil {
public static String getID(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
1、3Mapper接口
public interface blogMapper {
int addBlog(blog blog);
}
1、4Mapper配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Google.mapper.blogMapper">
<insert id="addBlog" parameterType="blog">
insert into blog (id,title,author,create_time,views)
values(#{id},#{title},#{author},#{createTime},#{views})
</insert>
</mapper>
1、5Mybatis配置
<?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>
<setting name="logImpl" value="STDOUT_LOGGING"/><!--日记log4j-->
<setting name="mapUnderscoreToCamelCase" value="true"/><!--开启驼峰命名规则-->
</settings>
<typeAliases>
<package name="com.Google.pojo"/><!--给实体类取别名-->
</typeAliases>
<!--<typeAliases>
<typeAlias type="com.Google.pojo.User" alias="user"/>
</typeAliases>-->
<environments default="development"><!--可以创建多个环境-->
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/><!--加载驱动-->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/><!--连接数据库-->
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--注册接口-->
<mappers>
<mapper resource="com/Google/Mapper/blogMapper.xml"/>
</mappers>
</configuration>
1、6用Java插入数据
package com.Google.mapper;
import com.Google.pojo.blog;
import com.Google.units.IDUtil;
import com.Google.units.sqlSessionFactory;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import javax.swing.*;
import java.util.Date;
public class blogTest {
@Test
public void test(){
SqlSession sqlSession = sqlSessionFactory.getsqlSession();
blogMapper mapper = sqlSession.getMapper(blogMapper.class);
blog blog = new blog();
blog.setId(IDUtil.getID());
blog.setTitle("Mybatis");
blog.setAuthor("小落");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
blog.setId(IDUtil.getID());
blog.setTitle("java");
mapper.addBlog(blog);
blog.setId(IDUtil.getID());
blog.setTitle("Spring");
mapper.addBlog(blog);
blog.setId(IDUtil.getID());
blog.setTitle("微服务");
mapper.addBlog(blog);
sqlSession.commit();
sqlSession.close();
}
}