MyBatis入门级Demo
1.创建Java工程MyBatisTest001,导入jar包(mybatis-3.2.1/mysql-connector-java-5.1.24-bin);
2.创建User表,数据库(MySql),字段信息见实体;
3.创建User实体:
package com.kaka.entity; public class User { private Integer id; private String username; private String password; private Integer age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
编写实体配置文件:
<?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="userTest"> <select id="selectUser" parameterType="int" resultType="com.kaka.entity.User"> select * from User where id = #{id} </select> </mapper>
4.创建配置文件:/MyBatisTest001/Resource/configuration.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> <typeAliases> <typeAlias type="com.kaka.entity.User" alias="User" /> </typeAliases> <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/work?characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/kaka/entity/UserMapper.xml"/> </mappers> </configuration>
5.编写测试用例:
package com.kaka.test; import java.io.Reader; 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.kaka.entity.User; public class MyBatisTest { public static void main(String[] args) throws Exception { String resource = "configuration.xml"; Reader reader = Resources.getResourceAsReader(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(reader); SqlSession sqlSession = sqlSessionFactory.openSession(); User user = sqlSession.selectOne("userTest.selectUser", 1); System.out.println(user.getUsername()); sqlSession.close(); } }
6.运行测试!