spring yBatis整合编程(Mysql 8)

本文介绍了如何将Spring与myBatis整合,详细讲解了从导入依赖、创建数据库到配置主配置文件spring.xml的每一步。在配置文件中,需要注意driverClassName改为com.mysql.cj.jdbc.Driver以适配MySQL 8,url中包含的特殊参数,以及sqlSessionFactory的typeAliasesPackage属性和MapperScannerConfigurer的basePackage设置。此外,还涉及到了持久层接口的实现和测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工程采用Maven管理

1. 导入依赖包

   <!-- 因为包的版本可能会换,所以直接定义一个变量来存储-->
   <properties>
        <spring.version>5.1.7.RELEASE</spring.version>
    </properties>
    <dependencies>
        <!--导入mysql和Mybatis相关的包,本文使用的是mysql8和5有区别-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!--        Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <!--        事务-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>
    </dependencies>

2.创建数据库(略)

3. 创建一个类存储表单记录

Department类(包路径为com.zju.mysm.entity,后面写配置文件的时候会用上)

public class Department {
    public Integer getId() {
        return id;
    }


    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }


    private Integer id;

    private String name;

    private String address;



}

有三个属性:id、name、address,写好setter和getter方法。

4. 创建一个持久层操作接口

DepartmentDao

@Repository("departmentDao")
public interface DepartmentDao {
    void insert(Department department);
    void delete(Integer id);
    void update(Department department);
    Department selectById(Integer id);
    List<Department> selectAll();

}

这里采用的是Repository注释,是SpringDAO层的Bean管理注释,采用注释的方式就不用去xml文件配置这个Bean了。

5.配置主配置文件spring.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"
       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.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- Spring整合Mybatis -->
    <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/sm?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=Asia/Shanghai&amp;zeroDateTimeBehavior=CONVERT_TO_NULL"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.zju.mysm.entity"/>
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.zju.mysm.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
    <!-- 声明式事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="search*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* com.zju.mysm.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
    <!-- 全局扫描 -->
    <context:component-scan base-package="com.zju.mysm"/>
    <aop:aspectj-autoproxy/>
</beans>

这其中有几点坑!!需要特别注意

- org.springframework.jdbc.datasource.DriverManagerDataSource类的driverClassName属性的值为com.mysql.cj.jdbc.Driver,老的mysql5采用的是com.mysql.jdbc.Driver(没有cj)

- url属性要设置为jdbc:mysql://localhost:3306/sm?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL,其中sm为你的数据库名称,&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL这一段是mysql8新加的(设置时区什么的,我也不是很清楚)

- 在 sqlSessionFactory这个bean中将typeAliasesPackage属性设置为前面的com.zju.mysm.entity这样,在写mapper的时候可以不用写整包路径(后面会说明)

- org.mybatis.spring.mapper.MapperScannerConfigurer用于扫描Dao接口的配置文件(xml文件)basePackage值为其包路径

6.配置持久层接口的实现xml文件

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespcae需要指定实现的接口的整包路径,type="Department"因为前面设置了所以没用整包路径-->
<mapper namespace="com.zju.mysm.dao.DepartmentDao">
    <resultMap id="resultMap" type="Department">
        <id property="id" column="id" javaType="Integer"/>
        <result property="name" column="name" javaType="String"/>
        <result property="address" column="address" javaType="String"/>
    </resultMap>

    <insert id="insert" parameterType="Department" useGeneratedKeys="true">
        insert into department(name,address) values(#{name},#{address})
    </insert>
    <delete id="delete" parameterType="Integer">
        DELETE FROM department WHERE id=#{id}
    </delete>
    <update id="update" parameterType="Department">
        UPDATE department SET name=#{name},address=#{address} WHERE id=#{id}
    </update>
    <select id="selectById" parameterType="Integer" resultMap="resultMap">
        SELECT * FROM department WHERE id=#{id}
    </select>
    <select id="selectAll" resultMap="resultMap">
        SELECT * FROM department
    </select>
</mapper>

resultMap标签是把数据库中的字段类型和java中的字段类型对应,属性设置中,主键用id其他用result

7.创建DepartmentService接口和实现类DepartmentServiceImpl

public interface DepartmentService {
    void add(Department department);
    void remove(Integer id);
    void edit(Department department);
    Department get(Integer id);
    List<Department> getAll();
}

@Service("departmentService")
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentDao departmentDao;

    public void add(Department department) {
        departmentDao.insert(department);
    }

    public void remove(Integer id) {
        departmentDao.delete(id);
    }

    public void edit(Department department) {
        departmentDao.update(department);
    }

    public Department get(Integer id) {
        return departmentDao.selectById(id);
    }

    public List<Department> getAll() {
        return departmentDao.selectAll();
    }
}

采用属性注入的方式将DepartmentDao注入

8.测试一下

创建一个Demo类进行测试

public class Demo {
    @Test

    public void demo(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        DepartmentService departmentService = (DepartmentService)applicationContext.getBean("departmentService");
        Department department = new Department();
        department.setId(1);
        department.setName("superman");
        department.setAddress("hhhhhhhhh");

        departmentService.add(department);
        List<Department> list = departmentService.getAll();
        for(Department mydepartment:list){
            System.out.println(mydepartment.getAddress());
        }

    }
}

由于是初学,肯定有很多理解不深刻的地方,望大家批评指正

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值