Java第三十七天,Mybatis框架系列,Mybatis入门案例——自定义Dao接口实现类
注意:
虽然自定义Dao接口实现类可以完成项目需求,但是通常情况下,开发项目很注重速度,因此本技术仅需掌握就行,实战应用几率很小!
1.新建Maven项目
2.在pom.xml配置文件中新增内容,最终如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.huhai</groupId>
<artifactId>demo10</artifactId>
<version>1.0-SNAPSHOT</version>
<!--新增内容-->
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
<!--新增内容-->
</project>
3.在 src\main\resources 目录新建 SqlMapConfig.xml 和 log4j.properties 配置文件,内容分别如下:
<?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="mysql"> <!--可为任意值,但该值必须出现在下面的 environment 标签中-->
<!--配置mysql环境-->
<environment id="mysql">
<!--事务类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置m数据源(连接池)-->
<dataSource type="POOLED">
<!--配置连接数据库的基本信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/> <!--数据库驱动-->
<property name="url" value="jdbc:mysql://localhost:3306/student"/> <!--指明哪个数据库-->
<property name="username" value="root"/> <!--数据库用户名-->
<property name="password" value="123456"/> <!--数据库用户名密码-->
</dataSource>
</environment>
</environments>
<!--用resource属性指明配置文件-->
<mappers>
<mapper resource="Dao/StuDao.xml"/>
</mappers>
</configuration>
# 全局日志配置
log4j.rootLogger=ERROR, stdout
# MyBatis 日志配置
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
4.创建数据库
create database student character set utf-8;
use student;
create table baseinfo (
student_id int unsigned not null primary key,
name char(10) not null,
sex char(4) not null,
birth date not null,
politily char(20) not null
);
insert into baseinfo values (201080701,"张三","男","1994-12-2","自动化1");
insert into baseinfo values (201080702,"李四","男","1989-10-8","自动化2");
insert into baseinfo values (201080703,"王五","男","1994-8-8","自动化2");
insert into baseinfo values (201080704,"路人1","女","1994-7-9","自动化2");
insert into baseinfo values (201080705,"路人2","男","1994-12-8","自动化2");
insert into baseinfo values (201080706,"路人3","女","1994-11-8","自动化2");
insert into baseinfo values (201080707,"路人4","男","1992-1-23","自动化2");
5.创建Student类如下,属性值需要与数据库中表的属性一一对应且相等
package Main;
import java.util.Date;
public class Student {
int student_id;
String name;
String sex;
Date birth;
String politily;
public int getStudent_id() {
return student_id;
}
public void setStudent_id(int student_id) {
this.student_id = student_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getPolitily() {
return politily;
}
public void setPolitily(String politily) {
this.politily = politily;
}
@Override
public String toString() {
return "Student{" +
"student_id=" + student_id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", birth=" + birth +
", politily='" + politily + '\'' +
'}';
}
}
6.创建StuDao.xml配置文件
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Dao.StuDao"> <!--namespace是指Dao的全限定域名,其中 . 代表目录,类似于 /-->
<!--查询-->
<!--有了它就能确定PreparedStatement,就可以执行配置文件中的SQL语句-->
<select id="findAll" resultType="Main.Student"> <!--id 必须和相应 JAVA Dao 接口文件抽象方法同名-->
select * from baseinfo; <!--sql语句结尾的封号可有可无-->
</select>
</mapper>
7.新建接口实现类StuDaoImpl
package Dao.Impl;
import Dao.StuDao;
import Main.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.Iterator;
import java.util.List;
public class StuDaoImpl implements StuDao {
private SqlSessionFactory factory;
//使用构造函数初始化 factory
public StuDaoImpl(SqlSessionFactory factory){
this.factory = factory;
}
public List<Student> findAll() {
//使用工厂创建sqlSession对象
SqlSession session = factory.openSession();
//使用session查询数据
//确定statement
List<Student> students = session.selectList("Dao.StuDao.findAll");
//关闭session
session.close();
//返回查询结果
return students;
}
}
8.新建实现类
package Main;
import Dao.Impl.StuDaoImpl;
import Dao.StuDao;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Realize {
public static void main(String[] args) throws IOException {
//读取配置文件
//因为读取配置文件的时候,绝对路径和相对路径都会出现很多问题,因此我们一般采用以下两种方法读取
//①使用类加载器(只能读取类路径的配置文件)
//②使用ServletContext对象的getRealPath()读取当前项目部署的绝对路径
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建工厂
//创建工厂时,mybatis使用了构建者模式,即找包工队盖房子,而不是自己亲自处理一系列问题
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//使用接口实现类创建接口对象
StuDao stuDao = new StuDaoImpl(factory);
//调用接口实现类的方法
List<Student> students = stuDao.findAll();
for(Student stu : students){
System.out.println(stu);
}
//释放资源
in.close();
}
}
9.项目架构
10.查询结果