12.动态SQL
动态SQL是指根据不同的条件,生成不同的SQL语句。
12.1随机生成id
public class IDutils {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
//测试
@Test
public void test1(){
System.out.println(IDutils.getId());
}
12.2开启驼峰命名映射
在mybatis-config.xml中
<!--开启字段名和驼峰命名转换,可以将数据表的create_time转换为createTime-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
12.3插入Blog数据
1。接口
//插入数据
int addBlog(Blog blog);
2.BlogMapper.xml
<insert id="addBlog" parameterType="blog">
INSERT INTO blog(id,title,auther,create_time,views) VALUES(#{id},#{title},#{auther},#{createTime},#{views});
</insert>
- parameterType是接口里面的参数,如int addBlog(Blog blog);只能**是blog,**其他类似
3.测试
@Test
public void test1(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog= new Blog();
blog.setId(IDutils.getId());
blog.setTitle("Mybatis好简单");
blog.setAuther("baba");
blog.setCreateTime(new Date());//当前时间
blog.setViews(9999);
mapper.addBlog(blog)