其他分享
首页 > 其他分享> > Spring+MyBatis

Spring+MyBatis

作者:互联网

1.创建数据库表

   #用户基本信息表

  create table t_sm(
    test_id int primary key auto_increment,
    test_name varchar(20),
    test_age int,
    test_address varchar(20)
  );

2.创建项目完善结构

   1.导入依赖

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.1.5.RELEASE</version>
</dependency>
<!-- spring-jdbc -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>5.1.5.RELEASE</version>
</dependency>
<!-- spring_tx -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>5.1.5.RELEASE</version>
</dependency>
<!-- MyBatis依赖 -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.4.6</version>
</dependency>
<!-- mybatis-spring 整合包 -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.3.1</version>
</dependency>
<!-- mysql数据库驱动 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.38</version>
</dependency>
<!--druid 阿里的连接池-->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.1.7</version>
</dependency>

   2.根据数据库表创建javabean

package com.wangxing.springmybatis.bean;

public class UserBean {
    private Integer testId;

    private String testName;

    private Integer testAge;

    private String testAddress;

    public Integer getTestId() {
        return testId;
    }

    public void setTestId(Integer testId) {
        this.testId = testId;
    }

    public String getTestName() {
        return testName;
    }

    public void setTestName(String testName) {
        this.testName = testName == null ? null : testName.trim();
    }

    public Integer getTestAge() {
        return testAge;
    }

    public void setTestAge(Integer testAge) {
        this.testAge = testAge;
    }

    public String getTestAddress() {
        return testAddress;
    }

    public void setTestAddress(String testAddress) {
        this.testAddress = testAddress == null ? null : testAddress.trim();
    }
}

   3.创建数据访问接口

package com.wangxing.springmybatis.mapper;

import com.wangxing.springmybatis.bean.UserBean;
import com.wangxing.springmybatis.bean.UserBeanExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;

@Component
public interface UserBeanMapper {
    long countByExample(UserBeanExample example);

    int deleteByExample(UserBeanExample example);

    int deleteByPrimaryKey(Integer testId);

    int insert(UserBean record);

    int insertSelective(UserBean record);

    List<UserBean> selectByExample(UserBeanExample example);

    UserBean selectByPrimaryKey(Integer testId);

    int updateByExampleSelective(@Param("record") UserBean record, @Param("example") UserBeanExample example);

    int updateByExample(@Param("record") UserBean record, @Param("example") UserBeanExample example);

    int updateByPrimaryKeySelective(UserBean record);

    int updateByPrimaryKey(UserBean record);
}

   4.在resources创建mapper文件夹统一保存所有映射文件

   5.在src/main/resources创建数据库链接字符串的资源文件【xxxxx.properties】

      mydata.properties

      mydriver = com.mysql.jdbc.Driver
      myurl = jdbc:mysql://127.0.0.1:3306/test
      myusername = root
      mypassword = 123456

   6.在src/main/resources配置MyBatis核心配置文件【mybatis-config.xml】中的内容融入Spring配置文件[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
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!--配置自动扫描seervice包    -->
    <context:component-scan base-package="com.wangxing.springmybatis.service.impl"></context:component-scan>
    <context:component-scan base-package="com.wangxing.springmybatis.Controller"></context:component-scan>
    <context:component-scan base-package="com.wangxing.springmybatis"></context:component-scan>
    <!--配置接在mydata.properties-->
    <context:property-placeholder location="mydata.properties"></context:property-placeholder>
    <!--配置数据源    -->
    <!-- com.alibaba.druid.pool.DruidDataSource-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${mydriver}"></property>
        <property name="url" value="${myurl}"></property>
        <property name="username" value="${myusername}"></property>
        <property name="password" value="${mypassword}"></property>
    </bean>
    <!--配置SqlSessionFactory    -->
    <!-- org.mybatis.spring.SqlSessionFactoryBean-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!--注入MyBatis配置文件        -->
        <!--<property name="configLocation" value="classpath:"></property>-->
        <!--注入sql映射文件路径-->
        <property name="mapperLocations" value="classpath:mapper/UserBeanMapper.xml"></property>
    </bean>
    <!--配置扫描数据库访问接口包,创建数据库访问接口对象    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wangxing.springmybatis.mapper"></property>
    </bean>
</beans>

   7.创建业务访问接口及其实现类

package com.wangxing.springmybatis.service;

import com.wangxing.springmybatis.bean.UserBean;
import org.springframework.stereotype.Component;

import java.util.List;
@Component
public interface UserService {
    public void insertUser(UserBean userBean);
    public void updateUser(UserBean userBean);
    public void deleteUser(int userid);
    public List<UserBean> selectUserByName(String name);
    public List<UserBean> selectUser();
}
package com.wangxing.springmybatis.service.impl;

import com.wangxing.springmybatis.bean.UserBean;
import com.wangxing.springmybatis.bean.UserBeanExample;
import com.wangxing.springmybatis.mapper.UserBeanMapper;
import com.wangxing.springmybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserBeanMapper userBeanMapper;
    @Override
    public void insertUser(UserBean userBean) {
        userBeanMapper.insert(userBean);
    }

    @Override
    public void updateUser(UserBean userBean) {
        userBeanMapper.updateByPrimaryKey(userBean);
    }

    @Override
    public void deleteUser(int userid) {
        userBeanMapper.deleteByPrimaryKey(userid);
    }

    @Override
    public List<UserBean> selectUserByName(String name) {
        UserBeanExample userBeanExample = new UserBeanExample();
        UserBeanExample.Criteria criteria = userBeanExample.createCriteria();
        criteria.andTestNameEqualTo(name);
        List<UserBean> userList = userBeanMapper.selectByExample(userBeanExample);
        return userList;
    }

    @Override
    public List<UserBean> selectUser() {
        List<UserBean> userList = userBeanMapper.selectByExample(null);
        return userList;
    }
}

   8.创建业务实类

package com.wangxing.springmybatis.Controller;

import com.wangxing.springmybatis.bean.UserBean;
import com.wangxing.springmybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import java.util.List;

@Component("userController")
public class UserController {
    @Autowired
    private UserService userService;

    public void add(UserBean userBean){
        try{
            userService.insertUser(userBean);
            System.out.println("添加成功");
        }catch(Exception e){
            System.out.println("添加失败");
            e.printStackTrace();
        }

    }

    public void upd(UserBean userBean){
        try{
            userService.updateUser(userBean);
            System.out.println("修改成功");
        }catch(Exception e){
            System.out.println("修改失败");
            e.printStackTrace();
        }

    }

    public void del(int id){
        try{
            userService.deleteUser(id);
            System.out.println("删除成功");
        }catch(Exception e){
            System.out.println("删除失败");
            e.printStackTrace();
        }

    }

    public List<UserBean> selOne(String name){
        try{
            List<UserBean> userList = userService.selectUserByName(name);
            System.out.println("查询成功");
            return userList;
        }catch(Exception e){
            System.out.println("查询失败");
            e.printStackTrace();
            return null;
        }
    }

    public List<UserBean> sel(){
        try{
            List<UserBean> userList = userService.selectUser();
            System.out.println("查询成功");
            return userList;
        }catch(Exception e){
            System.out.println("查询失败");
            e.printStackTrace();
            return null;
        }

    }
}

   9.测试代码

package com.wangxing.springmybatis;

import static org.junit.Assert.assertTrue;

import com.wangxing.springmybatis.Controller.UserController;
import com.wangxing.springmybatis.bean.UserBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;


public class AppTest {

    @Test
    public void ins() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserController userController = applicationContext.getBean("userController", UserController.class);
        UserBean userBean = new UserBean();
        userBean.setTestAddress("xian");
        userBean.setTestAge(23);
        userBean.setTestName("lisi");
        userController.add(userBean);

    }

    @Test
    public void upd() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserController userController = applicationContext.getBean("userController", UserController.class);
        UserBean userBean = new UserBean();
        userBean.setTestId(1);
        userBean.setTestAddress("xian");
        userBean.setTestAge(23);
        userBean.setTestName("lisi");
        userController.upd(userBean);
    }

    @Test
    public void del() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserController userController = applicationContext.getBean("userController", UserController.class);
        userController.del(3);

    }

    @Test
    public void selOne() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserController userController = applicationContext.getBean("userController", UserController.class);
        List<UserBean> list = userController.selOne("lisi");
        if(list!=null) {
            for (UserBean userBean : list) {
                System.out.println(userBean.getTestId() + "\t" + userBean.getTestName() + "\t" + userBean.getTestAge() + "\t" + userBean.getTestAddress());
            }
        }else {
            System.out.println("list为空");
        }
    }

    @Test
    public void sel() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserController userController = applicationContext.getBean("userController", UserController.class);
        List<UserBean> list = userController.sel();
        if(list!=null) {
            for (UserBean userBean : list) {
                System.out.println(userBean.getTestId() + "\t" + userBean.getTestName() + "\t" + userBean.getTestAge() + "\t" + userBean.getTestAddress());
            }
        }else {
            System.out.println("list为空");
        }
    }
}

 

标签:Spring,void,UserBean,MyBatis,import,userBean,com,public
来源: https://blog.csdn.net/m0_49935332/article/details/115720174