您的位置:首页 > 编程语言 > Java开发

Spring和Mybatis整合全过程实现(idea实现)适合初学spring和mybatis

2020-08-15 01:13 309 查看

推荐大家使用jdk1.8版本,否则后边的项目中可能会有问题

1.通过idea进行一个maven工程的创建,然后在pom文件中加入项目的依赖和bulider插件,直接用就可以了,如果你的依赖包中有的包没有,可以点一下右上角有一个刷新的标志进行更新下载,更新完之后字体就不会报红,就可以用了,下面给出我的pom文件,其中比较重要的依赖有Spring和mybatis的依赖,mysql的依赖,还有一个阿里云的数据源的依赖

[code]<?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.lin</groupId>
<artifactId>ch07-spring-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
</dependencies>

<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes>
<!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

2.编写一个Student实体类,写好set,get方法,有参和无参的构造方法,重写toString方法

[code]public class Student {
private int id;
private String name;
private String sex;

public Student() {
}

public Student(int id, String name, String sex) {
this.id = id;
this.name = name;
this.sex = sex;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = 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;
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
'}';
}
}

3.定义一个dao的接口,写这个接口就是方便以后如果业务进行修改的时候不会将原来的义务功能丢失,类似于一个电脑的内存条或者独立显卡,当你需要更换一个的时候,因为有一个可插拔的接口,可以将原来的拔下来进行替换,我在接口中定义的方法是插入和查询数据,因为插入和查询的数据都是对象,所以返回的结果存放在一个列表中,我们拿到之后只要进行遍历就行了。

[code]public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudent();
}

4.配置这个dao接口的配置文件,也就是我们所说的mapper映射文件,实际上,每一个dao接口都会对应一张表,也会对应一个xml文件,真正的sql语句就是写在这里边的,需要注意的是sql语句的id需要和dao接口中定义的方法名一致,其中返回值类型填实体类的所在路径

[code]<?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.lin.dao.StudentDao">
<insert id="insertStudent">
insert into student values(#{id},#{name},#{sex})
</insert>

<select id="selectStudent" resultType="com.lin.domain.Student">
select id,name,sex from student order by id desc
</select>
</mapper>

5.接下来写的就是我们的业务接口,其实这个接口中的方法功能才是我们开始所描述的业务功能,在实际的开发中,一个业务功能会对应多个dao接口,就是我们说的多表查询,而在初学的时候,我们通常会用一张表来学习,所以可能service接口中定义的方法会和dao中定义的方法名相同,但实际开发中不是这样的,这一点要清楚。

另外还要明白的是一个调用关系service→dao→数据库,实际上我们所要的业务功能是在service中实现的,但是如果不通过dao,直接进行一个业务功能的实现类的编写,我们的service功能就和数据的更新查询等功能过于耦合,假设你有一天想换用一个别的数据库查询语言,就很难修改,而通过dao,我们就不用对service中的代码进行修改,只需要将dao接口换下来,也就是进行了一个插拔的操作,修改一层的代码不影响其它层的代码,这样就实现了解耦合的目的。

[code]public interface StudentService {
int addStudent(Student student);
List<Student> queryStudents();
}

6.是service实现类的编写,其中需要注意的是需要写一个dao的set方法,这样spring在进行对象的声明时会进行set注入进行赋值操作

[code]
public class StudentServiceImpl implements StudentService {

private StudentDao studentDao;

//使用set注入
public void setStudentDao(StudentDao studentDao) {

this.studentDao = studentDao;
}

@Override
public int addStudent(Student student) {
int num = studentDao.insertStudent(student);
return num;
}

@Override
public List<Student> queryStudents() {
List<Student> students = studentDao.selectStudent();
return students;
}
}

7.是进行mybatis主配置文件的编写,其中只需要指明所有映射文件的位置就可以了,就是前面我们写的mapper文件,其他的交给spring统一管理

[code]<?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">
<!--mybatis的主配置文件-->
<configuration>
<!--设置mybatis的全局设置-->
<settings>
<!--打印日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

<!--设置别名-->
<typeAliases>
<!--name:实体类所在包名-->
<package name="com.lin.domain"/>
</typeAliases>

<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
<mappers>
<!--name:包名 这个包中的所有mapper.xml文件都能加载-->
<package name="com.lin.dao"/>
</mappers>
</configuration>

8.进行spring配置文件的编写,我们可以把spring看做一个容器,一个盛放对象的容器,我们项目中需要的所有对象,包括数据源对象都要交给spring,放在这个容器中统一进行管理,我们只要进行声明,在使用时只要通过这个对象的id就可以直接将这个对象拿来用,比较方便,还有我们之前需要创建dao代理对象时需要的SqlSessionFactory也要在这里声明,说明这个容器非常牛逼

[code]<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

<context:property-placeholder location="classpath:jdbc.properties"/>
<!--数据源-->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">

<!--连接数据库的信息,只需要修改value的值就可以-->
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

<!--声明的是mybatis中提供的SqlSessionFactoryBean类,在类的内部创建SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--set注入将数据库赋给了dataSource属性-->
<property name="dataSource" ref="myDataSource"/>
<!--mybatis主文件的位置-->
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>

<!--创建dao对象 使用SqlSession的getMapper()-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定使用对象的id-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--指定包名,包名是dao接口所在的包名,MapperScannerConfigurer会扫描指定包名中的所有接口,
并且执行getMapper()方法来生成每个接口的dao对象放在容器中-->
<property name="basePackage" value="com.lin.dao"/>
</bean>

<bean id="studentService" class="com.lin.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"/>
</bean>
</beans>

9.最后编写一个测试类进行功能测试,其中虽然是service调用了addStudent的方法,但实际上是将任务交给了代理对象也就是dao来执行,因为add方法实际上是调用了dao接口中的insert方法的,这样就十分巧妙的完成了插入的任务,中间其实通过代理dao对象来完成的。

[code]public class Test {
@org.junit.Test
public void serviceTestInsert(){
String config = "applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
//获取容器中的dao对象
StudentService service = (StudentService) ctx.getBean("studentService");

Student student = new Student();
student.setId(10);
student.setName("马华");
student.setSex("女");

int num = service.addStudent(student);
System.out.println("成功插入条数:" + num );
}

}

下边给出工程的代码结构图

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: