所需架包
1.mysql-connector-java-5.1.38.jar
2.mybatis-3.4.6.jar
项目结构
一、链接数据库配置文件config.properties
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\:///users
username=root
password=root
二、XML配置文件mybatis-config.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>
<properties resource="com/hp/config.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/hp/UserMapper.xml"/>
</mappers>
</configuration>
三、映射文件UserMapper.xml
resultType(这是一个坑)如果在mybatis-config.xml没有配置别名是不可以写User的要写全路径com.hp.User
<?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.hp.UserMapper">
<select id="selectUser" resultType="com.hp.User">
select * from user where id = #{id}
</select>
</mapper>
对应的java接口
package com.hp;
public interface UserMapper {
public User selectUser(int id);
}
四、实例
package com.hp;
import java.io.IOException;
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;
public class Test {
public static void main(String[] args) throws IOException {
String resource = "com/hp/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=sqlSessionFactory.openSession();
// User user = session.selectOne("com.hp.BlogMapper.selectUser", 1);
UserMapper mapper = session.getMapper(UserMapper.class);
User user= mapper.selectUser(2);
System.out.println(user);
session.close();
}
}
六、typeAliases类型别名
在mybatis-config.xml中配置
<typeAliases>
<typeAlias alias="User" type="com.hp.User"/>
</typeAliases>
这样配置在任何地方都可以通过User访问com.hp.User