Java第三十七天,Mybatis框架系列,Mybatis入门案例——XML配置方式
1.打开IDEA,新建项目,选择Maven,直接Next
2.配置项目属性,可以默认也可以自定义。GroupId尽量为域名反写,点击finish
3.编辑pom.xml配置文件添加如下属性:
①打包方式
<packaging>jar</packaging>
②导入mybatis坐标
进入mybatis官网
https://mybatis.org/mybatis-3/zh/index.html
选中入门,将依赖码复制到pom.xml <dependencies></dependencies> 标签中,如下:
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
</dependencies>
其中version可以自行编辑选择合适的版本
③导入Mysql坐标
在pom.xml <dependencies></dependencies> 标签中添加如下内容
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.7</version>
</dependency>
其中 version 版本自选适合当前项目的
④导入日志坐标(可选)
在pom.xml <dependencies></dependencies> 标签中添加如下内容
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.5</version>
</dependency>
其中 version 版本自选适合当前项目的
⑤导入单元测试坐标(可选)
在pom.xml <dependencies></dependencies> 标签中添加如下内容
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
其中 version 版本自选适合当前项目的
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.创建实体Java类开始进行逻辑操作
技巧:
①定义相关属性
②利用IDEA功能自动添加get、set、toString方法
③实体类中的属性名称要和数据库表中的属性名称一一对应且完全相同(注意)
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 + '\'' +
'}';
}
}
③创建持久层接口(行业规则为Dao包下xxxDao接口)
package Dao;
import Main.Student;
import java.util.List;
public interface StuDao {
List<Student> findAll();
}
6.在resources包下新建持久层XML管理文件(行业规则为SqlMapConfig.xml)
SqlMapConfig.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="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>
<!--指明映射配置文件路径,映射配置文件是指每个Dao独立的配置文件-->
<mappers>
<mapper resource="Dao/StuDao.xml"/> <!--该配置文件顶层路径是指resources当前目录下;本例中StuDao.xml的所在目录为src/xxx/resources/Dao/目录-->
</mappers>
</configuration>
StuDao.xml(由SqlMapConfig文件指定) 文件内容如下:
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Dao.StuDao"> <!--namespace是指Dao的全限定域名,其中 . 代表目录,类似于 /-->
<!--查询-->
<select id="findAll" resultType="Main.Student"> <!--id 必须和相应 JAVA Dao 接口文件抽象方法同名--> <!--resultType告知将程序的查询结果返回到Main.Student实体类对象中-->
select * from Student; <!--sql语句结尾的封号可有可无-->
</select>
</mapper>
7.添加日志功能
在 resources目录下新建 log4j.properties 文件,填入以下内容:
1og4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
1og4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
1og4j.appender.CONSOLE=org. apache.1og4j. ConsoleAppender
1og4j.appender.CONSOLE.layout=org. apache. log4j. PatternLayout
10g4j.appender.CONSOLE.1ayout.ConversionPattern=%d{IS08601} %-6r [%15.15t]%-5p%30.30c%x-% m\n
# LOGFILE is set to be a File appender using a PatternLayout.
1og4j.appender.LOGFILE=org. apache.1og4j. FileAppender
1og4j.appender.LOGFILE.File=d:\ axis. log
1og4j.appender.LOGFILE.Append=true
1og4j.appender.LOGFILE.layout=org. apache.1og4j. PatternLayout
1og4j.appender.LOGFILE.1ayout.ConversionPattern=%d{IS08601} %-6r [%15,15t]%-5p%30.30c%x-%m\n
8.创建测试类完成对功能的检验
package Main;
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);
//使用工厂模式生产session对象
//工厂模式降低了类之间的依赖关系(解耦)
SqlSession session = factory.openSession();
//使用session创建Dao接口代理对象(代理模式),注意这里我们并没有对Dao接口进行实现
//代理模式可以在不修改源码的基础上对已有模式进行增强
StuDao stuDao = session.getMapper(StuDao.class);
List<Student> students = stuDao.findAll();
System.out.println(students);
for(Student stu : students){
System.out.println(stu);
}
//释放资源
session.close();
in.close();
}
}