1.核心包
mysql-connector-java-5.1.21-bin.jar
mybatis-3.1.1.jar
2.其它jar
asm-3.3.1.jar
cglib-2.2.2.jar
commons-logging-1.1.1.jar
log4j-1.2.16.jar
slf4j-api-1.6.2.jar
slf4j-log4j12-1.6.2.jar
在mybatis开发中可获取
在项目中的结构是
3.mybatis.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> <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://127.0.0.1:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <!-- 这个是数据库操作的xml文件 --> <mapper resource="UserMapper.xml" /> </mappers> </configuration>
4.配置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.gzcgxt.erp.UserMapper"> <select id="select" resultType="com.gzcgxt.erp.hello.User"> select * from user where id = #{id} </select> </mapper>
5.创建一个User对象
package com.gzcgxt.erp.hello; import lombok.Data; @Data public class User { private Integer id; private String name; }
6.测试代码
package com.gzcgxt.erp.hello; 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; import org.junit.Test; public class App { //方式一 @Test public void sayHello() { // 获取当前程序的类加载器 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // 将mybatis配置文件和UserMaper文件读取进内存中 InputStream in = classLoader.getResourceAsStream("mybatis.xml"); // 构造mybatis工厂对像 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); // 获取连接 SqlSession session = factory.openSession(); // 查询单个User对象 User user = session.selectOne("com.gzcgxt.erp.UserMapper.select", 2); System.out.println(user); } //方式二 @Test public void sayHello2() throws Exception { InputStream in = Resources.getResourceAsStream("mybatis.xml"); // 构造mybatis工厂对像 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); // 获取连接 SqlSession session = factory.openSession(); // 查询单个User对象 User user = session.selectOne("com.gzcgxt.erp.UserMapper.select", 2); System.out.println(user); } }