初始Spring(终)之整合MyBaits

目录

12,整合MyBatis

12.1,回忆MyBaits

12.2,Mybati整合

13,声明式事务

1.回顾事务

2.Spring中事务的管理


12,整合MyBatis

步骤:

1.导入相关的jar包

  • junit
  • mybatis
  • mysql数据库
  • spring相关的
  • aop织入
  • mybatis-spring【new】

相关依赖:

    <dependencies>
        <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!-- mybatis驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!-- myBaits包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <!-- springmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.19</version>
        </dependency>
        <!-- Spring操作数据库需要spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.18</version>
        </dependency>
        <!-- 处理事务和AOP需要的包 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.9.1</version>
        </dependency>

        <!-- mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
    </dependencies>

2.编写配置文件 

3.测试

12.1,回忆MyBaits

1.编写实体类

2.编写核心配置文件

3.编写接口

4.编写Mapper.xml

5.测试

12.2,Mybati整合

1.编写Mapper实现类:

package com.xiao.Mapper;

import com.xiao.domain.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sqlSessionTemplate;

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    @Override
    public List<User> getUserList() {
        UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
        return mapper.getUserList();
    }
}

2.编写配置文件:

<?xml version="1.0" encoding="UTF8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.2.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">

    <!-- DataSource:使用Spring的数据源替换MyBaits的配置 c3p0 dbcp druid
         我们这里使用Spring提供的JDBC:
    -->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai"/>
        <property name="username" value="root"/>
        <property name="password" value="98526"/>
    </bean>

    <!-- 获取:sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
        <!-- 绑定MyBaits配置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 搜索映射xml文件-->
        <property name="mapperLocations" value="classpath:com/xiao/Mapper/*Mapper.xml"/>
    </bean>

    <!-- 获取:SqlSession注入 -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!-- 使用构造器注入,因为它没有set方法! -->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <!-- 向类注入:SqlSession注入 -->
    <bean id="userMapper" class="com.xiao.Mapper.UserMapperImpl">
        <property name="sqlSessionTemplate" ref="sqlSession"/>
    </bean>


</beans>

3.测试:

import com.xiao.Mapper.UserMapper;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;

public class Test01 {

    @Test
    public void test01() throws IOException {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapper userMapper1 = classPathXmlApplicationContext.getBean("userMapper", UserMapper.class);
        System.out.println(userMapper1.getUserList());
    }
}

第二种整合方式:

package com.xiao.Mapper;

import com.xiao.domain.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserMapperImpl02 extends SqlSessionDaoSupport implements UserMapper {


    @Override
    public List<User> getUserList() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.getUserList();
    }
}

直接继承:SqlSessionDaoSupport类该类中包含了SqlSessionTemplate 可以起到简化代码的作用!

13,声明式事务

1.回顾事务

  • 要把一组业务当成一个业务来做么一起成功要么一起失败!
  • 事务在项目开发中十分重要,设计到数据一致性的问题,不容马虎!
  • 确保完整性和一致性

事务的ACID原则:

  • 原子性
  • 一致性
  • 隔离性
    • 多个业务操作同一个资源防止数据损坏
  • 持久性
    • 事务一旦提交,无论系统发生什么问题,结果都不会在被影响,被持久化写到存储器中!

2.Spring中事务的管理

  • 声明式事务:AOP
  • 编程式事务:需要在代码中进行事务管理

思考:

为什么需要事务?

  •  如果不设置事务可能有数据库提交不一致的情况
  • 如果我们不在Spring中去配置声明事务,我们就需要在代码中手动去配置事务!
  • 事务在项目开发中十分重要,涉及数据的一致性和完整性,不容马虎!
<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

    <!-- DataSource:使用Spring的数据源替换MyBaits的配置 c3p0 dbcp druid
         我们这里使用Spring提供的JDBC:
    -->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai"/>
        <property name="username" value="root"/>
        <property name="password" value="98526"/>
    </bean>

    <!-- 获取:sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"/>
        <!-- 绑定MyBaits配置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 搜索映射xml文件-->
        <property name="mapperLocations" value="classpath:com/xiao/Mapper/*Mapper.xml"/>
    </bean>

    <!-- 获取:SqlSession注入 -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!-- 使用构造器注入,因为它没有set方法! -->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <!-- 配置声明式事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"/>
    </bean>

    <!-- 结合AOP实现事务的织入 -->
    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" >
        <!-- 给那些方法配置事务 -->
        <tx:attributes>
            <tx:method name="add" />
            <tx:method name="delete"/>
            <tx:method name="update"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>


    <!-- 配置事务切入 -->
    <aop:config>
        <aop:pointcut id="textPointcut" expression="execution(* com.xiao.Mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="textPointcut"/>
    </aop:config>

</beans>

如果你想要在Spring Boot中整合Mybatis Plus,并且在页面中渲染值,你可以按照以下步骤进行: 1. 配置Mybatis Plus 在Spring Boot项目中使用Mybatis Plus,需要在application.properties 或 application.yml文件中添加mybatis-plus的配置,例如: ``` mybatis-plus.mapper-locations=classpath*:mapper/**/*.xml mybatis-plus.type-aliases-package=com.example.demo.entity ``` 其中`mapper-locations`指定了mapper文件(xml)的位置,`type-aliases-package`指定了实体类的包名。 2. 配置Controller 编写Controller类,使用`@RequestMapping`注解来映射请求路径,例如: ``` @Controller public class UserController { @Autowired private UserService userService; @RequestMapping("/user") public String user(Model model) { List<User> userList = userService.list(); model.addAttribute("userList", userList); return "user"; } } ``` 在上述代码中,我们使用`@RequestMapping`注解映射路径为`/user`的请求,然后调用`userService.list()`方法获取用户列表,并将其添加到`Model`中。最后,返回`user`字符串,它表示我们将使用名为`user.html`的模板文件来渲染视图。 3. 配置Thymeleaf 在Spring Boot中,我们可以使用Thymeleaf作为模板引擎来渲染视图。在`pom.xml`文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 然后,在`application.properties`或`application.yml`文件中添加以下配置: ``` spring.thymeleaf.cache=false spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 ``` 其中,`spring.thymeleaf.prefix`指定了模板文件的位置,`spring.thymeleaf.suffix`指定了模板文件的后缀名。 4. 编写模板文件 在`src/main/resources/templates`目录下,创建一个名为`user.html`的文件,并编写以下代码: ``` <!DOCTYPE html> <html> <head> <title>User List</title> </head> <body> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr th:each="user : ${userList}"> <td th:text="${user.id}"></td> <td th:text="${user.name}"></td> <td th:text="${user.age}"></td> </tr> </tbody> </table> </body> </html> ``` 在上述代码中,我们使用Thymeleaf的语法来渲染用户列表。`th:each`指令用于遍历`userList`列表,并将每个用户的ID、姓名和年龄显示在表格中。 5. 运行程序 现在,我们可以启动程序并访问`http://localhost:8080/user`来查看用户列表。如果一切正常,你应该能够看到一个包含用户信息的表格。 希望以上步骤可以帮助你整合Mybatis Plus和Thymeleaf,在Spring Boot中渲染页面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

123小步

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值