-- Create the database named 'hbatis'.
-- It's OK to use `, not OK to use ' or " surrounding the database name to prevent it from being interpreted as a keyword if possible.
CREATE DATABASE IF NOT EXISTS `hbatis`
DEFAULT CHARACTER SET = `UTF8`;
-- Create a table named 'User'
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- Insert a test record
Insert INTO `user` VALUES ('1', 'john', '120', 'hangzhou,westlake');
4. com.john.hbatis.model.User类:
public class User {
private int id;
private String name;
private String age;
private String address;
// Getters and setters are omitted
// 如果有带参数的构造器,编译器不会自动生成无参构造器。当查询需要返回对象时,ORM框架用反射来调用对象的无参构造函数,导致异常:java.lang.NoSuchMethodException: com.john.hbatis.model.User.<init>()
// 这时需要明确写出:
public User() {
}
public User(int id, String address) {
this.id = id;
this.address = address;
}
public User(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
}
com/john/hbatis/model路径下的User.xml
<?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.john.hbatis.model.UserMapper">
<select id="getUserById" parameterType="int" resultType="User">
select * from `user` where id = #{id}
</select>
</mapper>
5. 测试类:
public class MyBatisBasicTest {
private static final Logger log = LoggerFactory.getLogger(MyBatisBasicTest.class);
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
@BeforeClass
public static void initial() {
try {
reader = Resources.getResourceAsReader("Configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
log.error("Error thrown while reading the configuration: {}", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
log.error("Error thrown while closing the reader: {}", e);
}
}
}
}
@Test
public void queryTest() {
SqlSession session = sqlSessionFactory.openSession();
User user = (User)session.selectOne("com.john.hbatis.model.UserMapper.getUserById", 1);
log.info("{}: {}", user.getName(), user.getAddress());
}
}