当前位置: 代码迷 >> 综合 >> 利用spring整合mybatis做 student crud
  详细解决方案

利用spring整合mybatis做 student crud

热度:81   发布时间:2023-12-03 09:54:30.0

1.首先我们先导入相关依赖。

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jdbc</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.45</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>3.3.2</version></dependency><!--dbcp连接池--><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.4</version></dependency><dependency><groupId>commons-pool</groupId><artifactId>commons-pool</artifactId><version>1.6</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>

2.我们进行spring事务配置(配置sqlSessionFactory,扫描映射文件(mapper动态代理),配置事务管理器,开启注解)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.3.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.3.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.3.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.3.xsd"
><context:component-scan base-package="com.hxci.jiangyunsong"/><context:property-placeholder location="classpath:database.properties"/><bean id="dataSource"  class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close" scope="singleton"><property name="driverClassName" value="${driver}" /><property name="url" value="${url}" /><property name="username" value="${user}" /><property name="password" value="${password}" /><property name="initialSize" value="${initialSize}"/><property name="maxActive" value="${maxActive}"/><property name="maxIdle" value="${maxIdle}"/><property name="minIdle" value="${minIdle}"/><property name="maxWait" value="${maxWait}"/><property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"/><property name="removeAbandoned" value="${removeAbandoned}"/></bean><!--配置sqlSessionFactory--><bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><!--<property name="configLocation" value="classpath:mybatis-config.xml"/>--><property name="typeAliasesPackage" value="com.hxci.**.pojo" ></property><property name="mapperLocations" value="classpath:mapper/*.xml"></property></bean><!--扫描映射文件(mapper动态代理)--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage"  value="com.hxci.**.dao"/></bean><!-- 配置事务管理器 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!-- 开启注解 --><mvc:annotation-driven/><!--transaction-manager="transactionManager"一定要加上,否则会报错,该配置是以事物的方式开启注解--><tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

3.加入映射文件

 customerMapper:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- 1.namespace:接口的一个路径 ,2.id :接口下抽象方法名3.接口的返回值和resultType 对应上 ,4接口的参数 对应上-->
<mapper namespace="com.hxci.jiangyunsong.dao.CustomerDao"><select id="query" resultType="com.hxci.jiangyunsong.pojo.Customer">select * from customer</select><insert id="add">insert  into  customer (username,jobs,phone) values (#{username},#{jobs},#{phone})</insert><delete id="delete">delete from customer where id=#{id}</delete><update id="update">update customer set username=#{username},jobs=#{jobs},phone=#{phone} where id=#{id};</update><select id="queryById" resultType="com.hxci.jiangyunsong.pojo.Customer">select * from customer where id=#{id}</select></mapper>

studentMapper:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- 1.namespace:接口的一个路径 ,2.id :接口下抽象方法名3.接口的返回值和resultType 对应上 ,4接口的参数 对应上-->
<mapper namespace="com.hxci.jiangyunsong.dao.StudentDao"><select id="query" resultType="com.hxci.jiangyunsong.pojo.Student">select * from student</select><insert id="add">insert  into student (username,sno) values (#{username},#{sno})</insert><delete id="delete">delete from student where id=#{id}</delete><update id="update">update student set username=#{username},sno=#{sno} where id=#{id};</update><select id="queryById" resultType="com.hxci.jiangyunsong.pojo.Student">select * from student where id=#{id}</select></mapper>

4.创建一个controller包,在包内创建CustomerController类

package com.hxci.jiangyunsong.controller;import com.hxci.jiangyunsong.pojo.Customer;
import com.hxci.jiangyunsong.pojo.Student;
import com.hxci.jiangyunsong.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;import java.util.List;@Controller
public class CustomerController {@AutowiredCustomerService service;public String query(){List<Customer> list = service.query();System.out.println(list);return null;}public String add(Customer customer,Student student){service.add(customer,student);return null;}public String update(Customer customer,Student student){service.update(customer,student);return null;}public void delete(Integer id){service.delete(id);}public String queryById(Integer id){Customer customer=service.queryById(id);System.out.println(customer);return null;}}

5.创建dao包,在dao包里创建两个接口CustomerDao和StudentDao

CustomerDao:

package com.hxci.jiangyunsong.dao;import com.hxci.jiangyunsong.pojo.Customer;import java.util.List;public interface CustomerDao {List<Customer> query();void add(Customer customer);void update(Customer customer);void delete(Integer id);Customer queryById(Integer id);}

StudentDao:

package com.hxci.jiangyunsong.dao;import com.hxci.jiangyunsong.pojo.Student;import java.util.List;public interface StudentDao {List<Student> query();void add(Student student);void update(Student student);void delete(Integer id);/*void queryById(Integer id);*/void queryById(Integer id);}

6.创建pojo包,在pojo包里创建两个用户实体类Customer和Student

Customer:

package com.hxci.jiangyunsong.pojo;public class Customer {private Integer id;private String username;private String jobs;private String phone;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getJobs() {return jobs;}public void setJobs(String jobs) {this.jobs = jobs;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}@Overridepublic String toString() {return "Customer{" +"id=" + id +", username='" + username + '\'' +", jobs='" + jobs + '\'' +", phone='" + phone + '\'' +'}';}
}

Student:

package com.hxci.jiangyunsong.pojo;public class Student {private Integer id;private String username;private String sno;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getSno() {return sno;}public void setSno(String sno) {this.sno = sno;}@Overridepublic String toString() {return "Student{" +"id=" + id +", username='" + username + '\'' +", sno='" + sno + '\'' +'}';}
}

7.创建service包,在service包里创建一个接口CustomerService和CustomerServiceImpl实现类

CustomerService:

package com.hxci.jiangyunsong.service;import com.hxci.jiangyunsong.pojo.Customer;
import com.hxci.jiangyunsong.pojo.Student;import java.util.List;public interface CustomerService {List<Customer> query();void add(Customer customer,Student student);void delete(Integer id);void update(Customer customer,Student student);Customer queryById(Integer id);}

CustomerServiceImpl:

package com.hxci.jiangyunsong.service.impl;import com.hxci.jiangyunsong.dao.CustomerDao;
import com.hxci.jiangyunsong.dao.StudentDao;
import com.hxci.jiangyunsong.pojo.Customer;
import com.hxci.jiangyunsong.pojo.Student;
import com.hxci.jiangyunsong.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.util.List;
@Service
public class CustomerServiceImpl  implements CustomerService   {@AutowiredCustomerDao dao ;@AutowiredStudentDao studentDao ;public List<Customer> query() {List<Customer> list = dao.query();return list;}public void add(Customer customer) {dao.add(customer);}@Transactionalpublic void add(Customer customer,Student student) {dao.add(customer);studentDao.add(student);}@Transactionalpublic void update(Customer customer,Student student) {dao.update(customer);studentDao.update(student);}@Transactionalpublic void delete(Integer id) {dao.delete(id);studentDao.delete(id);}@Transactionalpublic Customer queryById(Integer id){Customer queryById=dao.queryById(id);return queryById;}}

8.创建一个Test测试类,实现增删改查

package com.hxci.jiangyunsong;import com.hxci.jiangyunsong.controller.CustomerController;
import com.hxci.jiangyunsong.pojo.Customer;
import com.hxci.jiangyunsong.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestDemo {public static void main(String[] args) {ApplicationContext context =new ClassPathXmlApplicationContext("classpath:spring-mybatis.xml");for (String beanName : context.getBeanDefinitionNames()) {System.out.println(beanName + ":" + context.getBean(beanName));}CustomerController controller = (CustomerController)context.getBean("customerController");//添加/*Customer customer =new Customer();customer.setUsername("张三");customer.setPhone("12222222");customer.setJobs("java");Student student =new Student();student.setUsername("张三1");student.setSno("122222221");controller.add(customer,student);*//*//修改Customer customer =new Customer();customer.setId(1);customer.setUsername("张三11");customer.setPhone("787787887");customer.setJobs("javaweb");Student student =new Student();student.setId(1);student.setUsername("张三1");student.setSno("1223499994");controller.update(customer,student);*//* //删除controller.delete(2);*///查询一条/* Customer customer =controller.queryById(2);System.out.println(customer);*/Customer customer = new Customer();controller.queryById(2);}
}

  相关解决方案