前面maven项目新建与配置与各种可能出现的问题 可以参考 http://blog.csdn.net/frank_hsu_/article/details/79423420
这里就不赘述了。
表信息
CREATE TABLE `person_test` (
`ID` int(10) NOT NULL AUTO_INCREMENT,
`NAME` char(10) DEFAULT NULL,
`GENDER` int(1) DEFAULT NULL,
`ADDRESS` varchar(50) DEFAULT NULL,
`BRITHDAY` date DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
项目新建完成后修改pom.xml 配置
4.0.0
com
mybatis_test
war
0.0.1-SNAPSHOT
mybatis_test Maven Webapp
http://maven.apache.org
javax
javaee-api
7.0
org.mybatis
mybatis
3.2.7
mysql
mysql-connector-java
5.1.30
mybatis_test
org.apache.maven.plugins
maven-compiler-plugin
1.7
在src/main/resources 中新建 MyBatisCfg.xml 这里的事务后期会交由spring进行管理
在src/main/java 中新建 package : com.mybatis.mapper
编写 PersonTestMapper.xml文件
新建 package : com.mybatis.model 并建立实体类 Person.java
package com.mybatis.model;
import java.util.Date;
public class Person {
private Integer id;
private String name;
private Integer gender;
private String address;
private Date brithday ;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBrithday() {
return brithday;
}
public void setBrithday(Date brithday) {
this.brithday = brithday;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", gender=" + gender + ", address=" + address + ", brithday="
+ brithday + "]";
}
}
在src/test/java 建包 com.mybatis.test 添加测试类mybatisTest.java
package com.mybatis.test;
import java.io.InputStream;
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.mybatis.model.Person;
public class mybatisTest {
SqlSessionFactory sessionFactory;
@Before
public void setUp() throws Exception {
// 初始化
InputStream inputStream = Resources.getResourceAsStream("MyBatisCfg.xml");
sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void test() {
// 创建SqlSession
SqlSession sqlSession = sessionFactory.openSession();
// 命名空间com.mybatis.mapper.PersonTestMapper+.selectPersonById 找到对应SQL,傳入參數爲1
try {
Person person = sqlSession.selectOne("com.mybatis.mapper.PersonTestMapper.selectPersonById", 1);
System.out.println(person);
} finally {
sqlSession.close();
}
}
}
项目右键->Run As->JUnit Test,可以看到成功输出
Person [id=1, name=刘备, gender=1, address=蜀国, brithday=Wed Mar 21 00:00:00 CST 2018]
注意今天进行junit测试的时候出现了下面的错误(单纯进行某个某个方法出现下面的错误,如果都某个类进行测试,还不会出现)
下面给出解决方案
1.首先把junit4.4.jar的包 Remove 掉
2.然后 Add Library 选择如下
3.点击Next 最后点击选择 Junit4 最后OK 问题就解决了
(网上也有说,把Junit的包排到前面也可以解决该问题的)