标签:
create database mybatis;
use mybatis;
CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT);
INSERT INTO users(NAME, age) VALUES(‘Tom‘, 12);
INSERT INTO users(NAME, age) VALUES(‘Jack‘, 11);
<?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" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
public class User {
private int id;
private String name;
private int age;
//get/set方法
}
<?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="cn.imentors.mybatis.test1.UserMapper">
</mapper>
<!-- 根据id查询得到一个user对象 -->
<select id="getUserById" parameterType="int" resultType="cn.imentors.mybatis.test1.User">
select * from users where id=#{id}
</select>
</environments>
<mappers>
<mapper resource="cn/imentors/mybatis/test1/UserMapper.xml"/>
</mappers>
</configuration>
public class TestMain {
public static void main(String[] args) throws IOException {
String resource = "conf.xml";
//加载mybatis 的配置文件(它也加载关联的映射文件)
InputStream is = TestMain.class.getClassLoader().getResourceAsStream(resource);
//构建sqlSession 的工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
//创建能执行映射文件中sql 的sqlSession
SqlSession session = sessionFactory.openSession();
//映射sql 的标识字符串
String statement = "cn.imentors.mybatis.test1.UserMapper"+".getUserById";
//执行查询返回一个唯一user 对象的sql
User user = session.selectOne(statement, 1);
System.out.println(user);
}
}
标签:
原文地址:http://www.cnblogs.com/mentorStudio/p/4809281.html