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>
<typeAliases>
<typeAlias type="com.cj.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/stu" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<!-- Mapper映射文件 -->
<mappers>
<mapper resource="com/cj/mapper/UserMapper.xml" />
</mappers>
</configuration>
mapper.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">
<!-- 映射器名称空间,即UserDao对象的完整路径名
-->
<mapper namespace="com.cj.dao.UserDao">
<!--type的 User为别名config中<typeAliases>配置的-->
<resultMap type="User" id="luser">
<id column="id" property="id" />
<!-- 基本数据类型映射。column为数据库的列,property为该列所对应的Java属性 -->
<result column="name" property="name" /> <result column="age" property="age" />
</resultMap>
<!-- parameterType参数类型 ,resultType返回类型 -->
<select id="seluser" parameterType="String" resultType="User">
SELECT * FROM user WHERE name = #{name}
</select>
</mapper>
UserDao
package com.cj.dao;
import java.util.List;
import com.cj.entity.User;
public interface UserDao {
// 根据id查询
public User seluser(String name);
}
TestMain测试类
package com.cj.TestMain;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.cj.dao.UserDao;
import com.cj.entity.User;
public class TestMain{
public static void main(String[] args) throws Exception {
// 获得session(连接)
SqlSession openSession = new SqlSessionFactoryBuilder().build(Resources
.getResourceAsStream("config.xml")).openSession();
UserDao mapper = openSession.getMapper(UserDao.class);
User seluser = mapper.seluser("小娲女");
System.out.println(seluser.getName());
System.out.println(seluser.getAge());