mybatis和spring的整合
前置知识
1.什么叫做数据源?
在我们早前与数据库的开发中,我们使用JDBC(Java DataBase Connective)来和数据库进行交互,JDBC其实是Java中用于规范应用程序如何来访问数据库的应用程序接口(API),它提供了查询和更新数据库中数据的方法。(用JDBC驱动程序与数据库进行交互,其中最重要的一步就是获取与数据库的连接)。
数据源
数据源是对数据库以及对数据库交互操作的抽象,它封装了目标源的位置信息,验证信息和建立与关闭连接的操作。数据源可以看做程序中一个组件,它把传统中需要在代码里编写配置信息和获取连接等操作抽象出一个规范或者接口,这样不同的第三方可以自行实现该接口提供不同的策略。这样,数据源就是对应用程序是透明的,开发者只需为应用程序配置特定的数据源即可与数据库进行连接等操作。当需要更换数据库服务器或者更换数据库种类时,只需修改配置中信息即可,无需修改程序代码。
---就是将JDBC连接数据库的一套都封装好了,解耦合,不用像之前一样,如果使用不同的数据库,还要改代码。
数据源又分为带连接池和不带连接池。
例如阿里的druid,就是带连接池的
https://blog.csdn.net/weixin_36379084/article/details/116081139
2.mybatis中的#{}和${}的区别?
一般情况下能用#{}就用#{},能够防治sql注入
${},一般用来动态sql中使用
https://blog.csdn.net/qq_43589143/article/details/107424112
pom文件:
<?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.bjpowernode</groupId> <artifactId>ch07-spring-mybatis</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <!--单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--spring核心ioc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.5.RELEASE</version> </dependency> <!--做spring事务用到的--> <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> <!--mybatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <!--mybatis和spring集成的依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!--mysql驱动--> <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> <!--目的是把src/main/java目录中的xml文件包含到输出结果中。输出到classes目录中--> <resources> <resource> <directory>src/main/java</directory><!--所在的目录--> <includes><!--包括目录下的.properties,.xml 文件都会扫描到--> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> <!--指定jdk的版本--> <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>
里面用了将指定的文件打包到target中,一般的spring项目是不用这么设置的,因为我运行后能看到target有resource下面的文件。而普通的java项目,可能连resource都没有,这种全都需要自己建的文件,打包肯定不会将配置文件打到target中。
public interface StudentDao { int insertStudent(Student student); List<Student> selectStudents(); List<Student> selectStudentById(int id); }
<?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.bjpowernode.dao.StudentDao"> <insert id="insertStudent"> insert into student values(#{id},#{name},#{email},#{age}) </insert> <select id="selectStudents" resultType="Student"> select id,name,email,age from student order by id desc </select> <select id="selectStudentById" parameterType="int" resultType="Student"> select * from student where id = #{2} </select> </mapper>
注意namespace要指定绑定的接口文件。
public interface StudentService { int addStudent(Student student); List<Student> queryStudents(); List<Student> selectStudentById(int id); }
public class StudentServiceImpl implements StudentService { //引用类型 private StudentDao studentDao; //使用set注入,赋值 public void setStudentDao(StudentDao studentDao) { this.studentDao = studentDao; } @Override public int addStudent(Student student) { int nums = studentDao.insertStudent(student); return nums; } @Override public List<Student> queryStudents() { List<Student> students = studentDao.selectStudents(); return students; } @Override public List<Student> selectStudentById(int id) { List<Student> students = studentDao.selectStudentById(id); return students; } }
刚学习ssm项目的时候,就会感到疑问,为什么dao中已经有操作数据库中的方法了,为什么还在service包中在封装一层,继续调用dao包中对数据库操作的方法。其实这是解耦合,service是包含业务元素了,不仅仅是调用dao中的一个方法,而是要根据业务中的不同情况下调用dao中的方法。
applicationContext.xml
<?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"> <!-- 把数据库的配置信息,写在一个独立的文件,编译修改数据库的配置内容 spring知道jdbc.properties文件的位置 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!--声明数据源DataSource, 作用是连接数据库的--> <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!--set注入给DruidDataSource提供连接数据库信息 --> <!-- 使用属性配置文件中的数据,语法 ${key} --> <property name="url" value="${jdbc.url}" /><!--setUrl()--> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.passward}" /> <property name="maxActive" value="${jdbc.max}" /> </bean> <!--声明的是mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory的 SqlSessionFactory sqlSessionFactory = new .. --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--set注入,把数据库连接池付给了dataSource属性--> <property name="dataSource" ref="myDataSource" /> <!--mybatis主配置文件的位置 configLocation属性是Resource类型,读取配置文件 它的赋值,使用value,指定文件的路径,使用classpath:表示文件的位置 --> <property name="configLocation" value="classpath:mybatis.xml" /> </bean> <!--创建dao对象,使用SqlSession的getMapper(StudentDao.class) MapperScannerConfigurer:在内部调用getMapper()生成每个dao接口的代理对象。 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--指定SqlSessionFactory对象的id--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!--指定包名, 包名是dao接口所在的包名。 MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行 一次getMapper()方法,得到每个接口的dao对象。 创建好的dao对象放入到spring的容器中的。 dao对象的默认名称是 接口名首字母小写 --> <property name="basePackage" value="com.bjpowernode.dao"/> </bean> <!--声明service--> <bean id="studentService" class="com.bjpowernode.service.impl.StudentServiceImpl"> <property name="studentDao" ref="studentDao" /> </bean> </beans>
1.阿里的数据源
2.创建sqlSessionFactory(一个属性将数据源赋值,另一个属性是将mapper.xml中的StudentDao.xml等所在的包全部进行读取)
3.spring和mybatis的整合,将mybatis中生成的代理对象全部交到ioc中管理,sqlSessionFactory.getMapper()
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> <!--settings:控制mybatis全局行为--> <settings> <!--设置mybatis输出日志--> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!--设置别名--> <typeAliases> <!--name:实体类所在的包名 表示com.bjpowernode.domain包中的列名就是别名 你可以使用Student表示com.bjpowenrode.domain.Student --> <package name="com.bjpowernode.domain"/> </typeAliases> <!-- sql mapper(sql映射文件)的位置--> <mappers> <!-- name:是包名, 这个包中的所有mapper.xml一次都能加载 --> <package name="com.bjpowernode.dao"/> </mappers> </configuration>
jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/springdb jdbc.username=root jdbc.passward=123456 jdbc.max=30
=========================================================
全篇看下来,其实spring和mybatis的整合还是有点繁琐的,涉及到很多的配置文件、bean等等。确实springboot这块很方便,有很多都是已经整合好的。