标签:
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(32) NOT NULL, `birthday` date DEFAULT NULL, `sex` char(1) DEFAULT NULL, `address` varchar(256) DEFAULT NULL, PRIMARY KEY (`id`) );
<?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="123456" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/user.xml"/> </mappers> </configuration>
1 public class User { 2 public int id; 3 public String username; 4 public Date birthday; 5 public String sex; 6 public String address; 7 }
<?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="test"> <select id="getUserById" parameterType="int" resultType="cn.xleos.mybatisfirst.po.User"> SELECT * FROM user WHERE id = #{value} </select> </mapper>
public class MybatisFirstTest { private SqlSessionFactory sqlSessionFactory; @Before public void setUp() throws Exception { InputStream inputStream = Resources.getResourceAsStream("MybatisConfig.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void getUserByIdTest() { SqlSession sqlSession = sqlSessionFactory.openSession(); try { User user = sqlSession.selectOne("test.getUserById", 1); System.out.println(user); }finally{ sqlSession.close(); } } }
标签:
原文地址:http://www.cnblogs.com/xialiang/p/4565145.html