例子:mybatis根据用户id主键查询用户信息
版本 文件目录:
maven: apache-maven-3.5.0 idea: 2017.3 mybatis: 3.3.2 1、建立与数据库表对应的实体类及log4j.properties我的sql数据库表结构 file:///C:/Users/hasee/AppData/Local/Temp/msohtmlclip1/01/clip_image002.png 实体类(一定需要同数据库结构对应以完成映射) public class User {
private Stringname;
private String password;
private int id;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public StringgetPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public StringgetSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public StringtoString() {
return "User{"+
"name='" + name+ '\'' +
", password='" + password+ '\'' +
", id=" + id +
", sex='" + sex + '\'' +
'}'; }
} Log4j.propertis配置(用于分析日志信息) # Configure loggingfor testing: optionally with log file
log4j.rootLogger=WARN,stdout
# log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n 2、配置映射文件(输入和输出映射) 文件命名:xxxxMybatis.xml 在映射文件中配置sql语句 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTDMapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Hello.entity.User"><!—namepace:由于区分sql代码块--> <!-- id:分辨sql语句标识 parameterType:输入类型(也就是占位符id的类型
resultType:当sql语句执行查询到的返回值类型(对应实体类) )-->
<select id="userMapper"parameterType="int" resultType="com.Hello.entity.User">
SELECT * FROM userid WHERE id=#{id}<!-- #{id}表占位符-->
</select>
</mapper> 1、 配置mybatis-config.xml(mybatis的核心配置)2、 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTDConfig 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="callSettersOnNulls"value="true" />
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
<environments default="development">
<environment id="development">
<!--使用了 JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务作用域-->
<transactionManager type="JDBC"/>
<!--使用数据池(数据源),复用实例-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/> <!--连接数据库地址-->
<property name="url" value="jdbc:mysql://localhost:3306/数据库名"/>
<property name="username" value="root"/><!—数据库id-->
<property name="password" value="root"/><!—数据库密码-->
</dataSource>
</environment>
</environments>
<mappers> <!—resource属性为:映射文件的地址 idea可以用Ctrl+Alt+Shift+C -->
<mapper resource="mapper/userMapper.xml"></mapper>
</mappers>
</configuration> 4、具体实现代码配置实现类(创建sql静态工厂)需要使用到的包调用类时注意即可 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;
import java.io.IOException;
import java.io.Reader; 具体代码 public class MybatisUserFirst {
//根据id查询用户得到一条数据的结果
@Test //使用注解的方式测试运行
public void findUserByIdTest() throws IOException {
//得到配置文件
//InputStreaminputStream=Resources.getResourceAsStream("mybatis-config.xml");使用字节流
Reader inputStream=Resources.getResourceAsReader("mybatis-config.xml");
//创建会话工厂,在build中添加配置文件的信息
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
//通过工厂得到SqlSession
SqlSession sqlSession=sqlSessionFactory.openSession();
//通过SqlSession操作数据库 selectOne 查询一条记录
//第一个参数为statement中的id 也就是<mapper namespace="">+语句中的id属性
//第二个参数parameter 也就是填充sql语句中的占位符
UserId user= sqlSession.selectOne("user.UserId.findUser",1);
System.out.println(user);
}
} 分析: SqlSessionFactory sqlSessionFactory=new qlSessionFactoryBuilder().build(inputStream); 可以说每个MyBatis都是以一个SqlSessionFactory实例为中心的。SqlSessionFactory实例可以通过SqlSessionFactoryBuilder来构建,他是创建sqlSessionFactory的入口类。 SqlSession sqlSession=sqlSessionFactory.openSession(); 我们已经创建了SqlSession工厂了现在需要用这个工厂为我们创建openSession(Session 会话 PS:不太了解工厂的可以看看Java的工厂模式,会话是同数据库单独的一对一的连接)
Maven中pom.xml注入mybatis依赖 <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<!--https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
|