第一步,新建工程导包
核心包::
理论上有这两个就足够了
第二步,写xml配置文件以及bean和dao和dao实现和mapper
Mybatis的xml配置文件:
这个配置文件主要用来使用jdbc连接数据库,以及制定mapper文件位置
sqlMybatis.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="username" value="root"/>
<property name="password" value="302501"/>
<property name="url" value="jdbc:mysql://localhost:3306/shixun"/>
<property name="driver" value="com.mysql.jdbc.Driver"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="Tb_bbsDao.xml"/>
</mappers>
</configuration>
bean文件
bean文件是数据库内容往java方面的封装,一般直接写上属性,自动生成get和set方法
tb_bbs.java
package com.atxiaoming.bean;
public class Tb_bbs {
private Integer id;
private String title;
private String content;
private String intime;
//我创建两个构造方法,方便插入
public Integer getId() {
return id;
}
public Tb_bbs() {
super();
}
public Tb_bbs(Integer id, String title, String content, String intime) {
super();
this.id = id;
this.title = title;
this.content = content;
this.intime = intime;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getIntime() {
return intime;
}
public void setIntime(String intime) {
this.intime = intime;
}
}
dao接口;
dao接口只定义方法,实现在Test mapper中,或者实现类中提供
tb_bbsDao.java
package com.atxiaoming.dao;
import java.util.List;
import com.atxiaoming.bean.Tb_bbs;
public interface Tb_bbsDao {
//增加
public int addTb_bbs(Tb_bbs bbs);
//删除
public void deleteTb_bbs(Integer id);
//修改
public int updateTb_bbs(Tb_bbs t);
// java.lang.IllegalArgumentException:Mapped Statements collection does not contain
//全查询
public List<Tb_bbs> selectAll();
//指定查询
public List<Tb_bbs> selectById(Integer id);
}
dao实现:
接口实现类,可用可不用,使用这个主要是简化测试,直接调用方法即可
tb_bbsDaoImpl.java
package com.xiaoming.daoImpl;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.atxiaoming.bean.Tb_bbs;
import com.atxiaoming.dao.Tb_bbsDao;
public class Tb_bbsDaoImpl implements Tb_bbsDao{
/*
* (non-Javadoc)
* @see com.lanqiao.dao.Tb_bbsDao#addTb_bbs(com.lanqiao.vo.Tb_bbs)
*
* 1 读取配置文件(连接数据库)
* 2 建立工厂模式
* 3打开session
* 4调用增删改查方法
* 5提交事务(增删改) /集合传值
* 6关闭session
*/
static SqlSessionFactory sf=null;
static{
try {
Reader reader=Resources.getResourceAsReader("sqlMybatis.xml");
sf=new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//增加
@Override
public int addTb_bbs(Tb_bbs bbs) {
// TODO Auto-generated method stub
SqlSession ss=sf.openSession();
int i=ss.insert("addTb_bbs", bbs);
ss.commit();
ss.close();
return i;
}
//删除
@Override
public void deleteTb_bbs(Integer id) {
// TODO Auto-generated method stub
SqlSession ss=sf.openSession();
ss.delete("deleteTb_bbs", id);
ss.commit();
ss.close();
}
//修改
@Override
public int updateTb_bbs(Tb_bbs bbs) {
// TODO Auto-generated method stub
SqlSession ss=sf.openSession();
int i=ss.update("updateTb_bbs", bbs);
ss.commit();
ss.close();
return i;
}
@Override
public List<Tb_bbs> selectAll() {
// TODO Auto-generated method stub
SqlSession ss=sf.openSession();
List<Tb_bbs> list=ss.selectList("selectAll");
for(Tb_bbs t:list){
System.out.println(t.getId()+"--"+t.getTitle()
+"--"+t.getContent()+"--"+t.getIntime());
}
ss.close();
return list;
}
//指定查询
@Override
public List<Tb_bbs> selectById(Integer id) {
// TODO Auto-generated method stub
SqlSession ss=sf.openSession();
List<Tb_bbs> list=ss.selectList("selectById",id);
for(Tb_bbs t:list){
System.out.println(t.getId()+"--"+t.getTitle()
+"--"+t.getContent()+"--"+t.getIntime());
}
ss.close();
return list;
}
}
mapper映射文件:
mapper映射文件,必须的,负责SQL语句的编写,动态SQL的检查,注意,当不写接口实现类的时候,
就把mapper文件中的id和dao接口方法对应,方便实现
tb_bbsDao.mapper
<?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="com.atxiaoming.dao.Tb_bbsDao">
<insert id="addTb_bbs" >
insert into tb_bbs values(null,#{title},#{content},#{intime});
</insert>
<delete id="deleteTb_bbs" parameterType="com.atxiaoming.bean.Tb_bbs">
delete from tb_bbs where id=#{id};
</delete>
<update id="updateTb_bbs" parameterType="com.atxiaoming.bean.Tb_bbs">
update tb_bbs set
<if test="title!=null">
title=#{title}
</if>
<if test="(title!=null) and (content!=null)">
,
</if>
<if test="content!=null">
content=#{content}
</if>
<if test="(content!=null) and (intime!=null)">
,
</if>
<if test="intime!=null">
intime=#{intime}
</if>
where id=#{id};
</update>
<select id="selectAll" resultType="com.atxiaoming.bean.Tb_bbs">
select * from tb_bbs;
</select>
<select id="selectById" resultType="com.atxiaoming.bean.Tb_bbs">
select * from tb_bbs where id=#{id};
</select>
</mapper>
好的主要文件就这几个:
第三步,测试
可以先导入log4j日志,方便查看和测试
日志文件也是,可要可不要
log4j.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
之后创建Junit进行测试,
bbsTest.java
package com.atxiaoming.Test;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import com.atxiaoming.bean.Tb_bbs;
import com.atxiaoming.dao.Tb_bbsDao;
import com.xiaoming.daoImpl.Tb_bbsDaoImpl;
public class bbsTest {
SqlSessionFactory sqlSessionFactory;
@Test
public void testDelete() {
SqlSession openSession = sqlSessionFactory.openSession();
try {
Tb_bbsDao bbsDao = openSession.getMapper(Tb_bbsDao.class);
bbsDao.deleteTb_bbs(4);
openSession.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testUseImpl() {
//创建实现类进行测试
Tb_bbsDaoImpl tb = new Tb_bbsDaoImpl();
// 首先测试用实现类插入
// tb.addTb_bbs(new Tb_bbs(null, "看看", "试试", "2020-01-05"));
//接下来测试删除
// tb.deleteTb_bbs(8);
//然后测试修改
// Tb_bbs bbs= new Tb_bbs();
// bbs.setId(20);
// bbs.setTitle("样样19块");
// bbs.setContent("最后几天");
// bbs.setIntime("2020-06-18");
// tb.updateTb_bbs(bbs);
//
//最后:测试查询
tb.selectAll();
}
@Test
public void testAdd() {
// 获取回话
SqlSession openSession = sqlSessionFactory.openSession();
// 获取mapper
try {
Tb_bbsDao bbsDao = openSession.getMapper(Tb_bbsDao.class);
int i = bbsDao.addTb_bbs(new Tb_bbs(null, "看看", "试试", "2020-01-05"));
System.out.println(i);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testSelect() {
// 2、获取回话
SqlSession openSession = sqlSessionFactory.openSession();
// 3、调用getmapper获取dao借口
try {
Tb_bbsDao bbsDao = openSession.getMapper(Tb_bbsDao.class);
List<Tb_bbs> list = bbsDao.selectById(1);
for (Tb_bbs tb_bbs : list) {
System.out.println(tb_bbs);
}
} finally {
openSession.close();
}
}
// 在其他Test运行之前执行这个初始化建工厂操作
@Before
public void restart() throws IOException {
// 1、构建sqlsessionfactory
String resource = "sqlMybatis.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
}
然后,这个模块是专门用实现类进行测试的:
首先,展示所有数据:
和数据库对比
查询成功:
然后测试插入:
执行结果:
id为14的结果就是新增的,因为我设置的是id自增,前面测试很多次了
其余的操作也是类似,我就不赘述了