Spring框架学习笔记——整合mybatis

实现spring整合mybatis步骤:
1.新建maven项目
2.加入maven的依赖
1)spring依赖
2)mybatis依赖
3)mysql依赖
4)spring的事务的依赖
5)mybatis和spring集成的依赖:mybatis官方体用的,用来在spring项目中创建mybatis的SqlSessionFactory,dao对象的



<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.0modelVersion>

  <groupId>com.wxxgroupId>
  <artifactId>ch07-spring-mybatisartifactId>
  <version>1.0-SNAPSHOTversion>

  <name>ch07-spring-mybatisname>
  
  <url>http://www.example.comurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
  properties>

  <dependencies>

    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>5.2.5.RELEASEversion>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>5.2.5.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>5.2.5.RELEASEversion>
    dependency>

    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.5.1version>
    dependency>

    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.1version>
    dependency>

    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.34version>
    dependency>

    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.1.12version>
    dependency>

  dependencies>

  <build>

   <resources>
     <resource>
       <directory>src/main/javadirectory>
       <includes>
         <include>**/*.propertiesinclude>
         <include>**/*.xmlinclude>
       includes>
       <filtering>falsefiltering>
     resource>

   resources>

    <plugins>
      <plugin>
        <artifactId>maven-compiler-pluginartifactId>
        <version>3.1version>
        <configuration>
          <source>1.8source>
          <target>1.8target>
        configuration>
      plugin>
    plugins>
  build>
project>

3.创建实体类

package com.wxx.domain;

public class Student {
    //属性名与列名一样
    private  Integer id;
    private  String name;
    private  String email;
    private  Integer age;


    public Student() {
    }

    public Student(Integer id, String name, String email, Integer age) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.age = age;
    }

    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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

4.创建dao接口和mapper文件

package com.wxx.dao;

import com.wxx.domain.Student;

import java.util.List;

public interface StudentDao {

    int insertStudent(Student  student);
    List<Student> selectStudents();
}




<mapper namespace="com.wxx.dao.studentDao">
        <insert id="insertStudent">
            insert into student values{#{id},#{name},#{email},#{age})
        insert>

    <select id="selectStudent" resultType="com.wxx.domain.Student">
        select id,name,email,age from student order by id desc

    select>

mapper>    

5.创建mybatis主配置文件



<configuration>
    
    <settings>
        
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>


    
    <typeAliases>
        
        <package name="com.wxx.domain"/>
    typeAliases>

    
    <mappers>
        

        <package name="com.wxx.dao"/>
    mappers>
configuration>

6.创建service接口和实现类,属性是dao

package com.service;

import com.wxx.domain.Student;

import java.util.List;

public interface StudentService {
    int addStudent(Student student);
    List<Student> queryStudents();
}

package com.service.impl;

import com.service.StudentService;
import com.wxx.dao.StudentDao;
import com.wxx.domain.Student;

import java.util.List;

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;
    }
}

7.创建spring的配置文件:声明mybatis的对象交给spring创建
1)数据源
2)SQLSessionFactory
3)dao对象
4)声明自定义的service


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">

        <property name="url" value="jdbc:mysql://localhost:3306/how2java"/>
        <property name="username" value="root"/>
        <property name="password" value="admin"/>
        <property name="maxActive" value="20"/>

    bean>


    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <property name="dataSource" ref="myDataSource"/>

        <property name="configLocation" value="classpath:mybatis.xml"/>
    bean>


    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

        <property name="basePackage" value="com.wxx.dao"/>
    bean>

beans>

8.创建测试类,获取Service对象,通过service调用dao完成数据库的访问

package com.wxx;

import com.service.StudentService;
import com.wxx.dao.StudentDao;
import com.wxx.domain.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class Mytest {
    @Test
    public void test01(){
        String config="applicationContext.xml";
        ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
        String names[]= ctx.getBeanDefinitionNames();
        for(String na:names){
            System.out.println("容器中对象名称"+na+"|"+ctx.getBean(na));
        }
    }

    @Test
    public void testServiceInsert(){

        String config="applicationContext.xml";
        ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
        //获取Spring容器中的dao对象
        StudentService service = (StudentService) ctx.getBean("studentService");
        Student student=new Student();
        student.setId(1003);
        student.setName("李四");
        student.setEmail("[email protected]");
        student.setAge(23);
        int nums =service.addStudent(student);
        //spring和mybatis整合在一起使用,事务自动提交,无需执行sqlsession.commit();
        System.out.println("nums="+nums);
    }

    @Test
    public void testServiceSelect(){

        String config="applicationContext.xml";
        ApplicationContext ctx=new ClassPathXmlApplicationContext(config);
        //获取Spring容器中的dao对象
        StudentService service=(StudentService)ctx.getBean("studentService");
        List<Student> students=service.queryStudents();
        for(Student stu:students){
            System.out.println(stu);
        }
    }
}

testServiceInsert()运行结果:Spring框架学习笔记——整合mybatis_第1张图片
数据库:
Spring框架学习笔记——整合mybatis_第2张图片
testServiceSelect()运行结果:
Spring框架学习笔记——整合mybatis_第3张图片
总结:在applicationContext.xml中spring创建了三个 bean标签中的对象,第一个是数据库连接对象,然后创建dao和service,通过service来操作dao。

你可能感兴趣的:(mybatis,java,spring)