- SQL
- 第一步:建立实体类
- 建立Blog类
- 第二步:建立Mapper接口
- 建立BlogMapper接口
- 第三步:建立Mapper.XML文件
- 建立BlogMapper.XML文件
- 第四步:在核心配置文件中绑定注册我们的Mapper接口或者文件
- 第五步:建立工具类:实现UUID
- 第六步:测试类:插入数据
- 文件结构:
SQL
CREATE TABLE blog( id varchar(50) not null comment '博客id', title varchar(100) not null comment '博客标题', author varchar(30) not null comment '博客作者', create_time datetime not null comment '创建时间', views int(30) not null comment '浏览量' )第一步:建立实体类 建立Blog类
package org.pojo;
import java.util.Date;
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;//属性名和字段名不一致
private int views;
@Override
public String toString() {
return "Blog{" +
"id='" + id + ''' +
", title='" + title + ''' +
", author='" + author + ''' +
", createTime=" + createTime +
", views=" + views +
'}';
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
}
第二步:建立Mapper接口
建立BlogMapper接口
package org.dao;
import org.pojo.Blog;
public interface BlogMapper {
//插入数据
int addBlog(Blog blog);
}
第三步:建立Mapper.XML文件
建立BlogMapper.XML文件
第四步:在核心配置文件中绑定注册我们的Mapper接口或者文件insert into mybatis.blog (id,title,author,create_time,views) values (#{id},#{title},#{author},#{createTime},#{views})
第五步:建立工具类:实现UUID
package org.utils;
import java.util.UUID;
@SuppressWarnings("all")//抑制警告
public class IDutils {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
第六步:测试类:插入数据
import org.apache.ibatis.session.SqlSession;
import org.dao.BlogMapper;
import org.junit.Test;
import org.pojo.Blog;
import org.utils.IDutils;
import org.utils.MybatisUtils;
import java.util.Date;
public class MyTest {
@Test
public void addInitBlog(){
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDutils.getId());
blog.setTitle("Mybatis如此简单!!!");
blog.setAuthor("lyh");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
blog.setId(IDutils.getId());
blog.setTitle("Java如此简单!!!");
mapper.addBlog(blog);
blog.setId(IDutils.getId());
blog.setTitle("MySQL如此简单!!!");
mapper.addBlog(blog);
blog.setId(IDutils.getId());
blog.setTitle("Spring如此简单!!!");
mapper.addBlog(blog);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
}catch(Error e){
e.printStackTrace();
}finally {
sqlSession.close();
}
}
}
文件结构:



