User.java实体类
public class User { private int id; private String username; private int age; //... }//数据库表对应实体类
userMapper.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"> <mapper namespace="com.mybatis.beans.userMapper"> <!-- 根据id查询得到一个user对象 --> <select id="getUser" parameterType="int" resultType="com.mybatis.beans.User"> select * from users where id=#{id} </select> </mapper>
conf.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> <!-- development 开发模式 work 工作模式 --> <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="com/mybatis/beans/userMapper.xml"/> </mappers> </configuration>
测试方法
import java.io.IOException; 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; public class Test { public static void main(String[] args) throws IOException { String resource = "conf.xml"; //加载Mybatis的配置文件(它也加载关联的映射文件) Reader reader = Resources.getResourceAsReader(resource); //构建SqlSession的工厂 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); //创建能执行映射文件中SQL语句的SqlSession SqlSession session = sessionFactory.openSession(); //映射SQL的标识字符串 String s = "com.mybatis.beans.userMapper" + ".getUser"; //执行查询返回一个唯一的User对象 User user = session.selectOne(s, 3); System.out.println(user); } }
或者使用下面的方法测试
public static void test() { String resource = "conf.xml"; InputStream inputStream = Test.class.getClassLoader().getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = factory.openSession(); String s = "com.mybatis.beans.userMapper" + ".getUser"; User user = session.selectOne(s, 3); System.out.println(user); }
可以写一个工具类来获取SqlSessionFactory
import java.io.InputStream; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.mybatis.beans.Test; public class MybatisUtil { public static SqlSessionFactory getFactory() { String resource = "conf.xml"; InputStream inputStream = Test.class.getClassLoader().getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); return factory; } }
http://yunpan.cn/cgwRwJYafX3sv 提取码 fad7
时间: 2024-11-05 16:34:01