Home  >  Article  >  Java  >  Introduction and configuration details of mybatis

Introduction and configuration details of mybatis

黄舟
黄舟Original
2017-09-02 11:14:401326browse

This article mainly introduces the introduction and configuration of mybatis, and introduces the simple configuration of MyBatis+Spring+MySql. Those who are interested can learn more

Introduction to MyBatis

MyBatis is a persistence layer framework that can customize SQL, stored procedures and advanced mapping. MyBatis eliminates most of the JDBC code, manual setting of parameters and result set retrieval. MyBatis only uses simple XML and annotations to configure and map basic data types, Map interfaces and POJOs to database records. Compared with "one-stop" ORM solutions such as Hibernate and Apache OJB, Mybatis is a "semi-automated" ORM implementation.
Jar package required: mybatis-3.0.2.jar (mybatis core package). mybatis-spring-1.0.0.jar (package combined with Spring).

MyBatis+Spring+MySql simple configuration

Build a Spring environment

1, Create a maven web project;
2, Add the Spring framework and configuration files;
3, Add the required jar packages (spring framework, mybatis, mybatis-spring, junit) to pom.xml etc.);
4, change the web.xml and spring configuration files;
5, add a jsp page and corresponding Controller;
6, test.

Create a MySql database

Create a student course selection management database.

Table: student table, class table, teacher table, course schedule, student course selection table.

Logical relationship: each student has a class; each class corresponds to a class teacher; each teacher can only be the class teacher of one class;

Use the following To build a database using sql, first create a student table and insert data (more than 2 items).

For more sql, please download the project source file in resource/sql.


/* 建立数据库 */ 
CREATE DATABASE STUDENT_MANAGER; 
USE STUDENT_MANAGER; 
 
/***** 建立student表 *****/ 
CREATE TABLE STUDENT_TBL 
( 
  STUDENT_ID     VARCHAR(255) PRIMARY KEY, 
  STUDENT_NAME    VARCHAR(10) NOT NULL, 
  STUDENT_SEX    VARCHAR(10), 
  STUDENT_BIRTHDAY  DATE, 
  CLASS_ID      VARCHAR(255) 
); 
 
/*插入**/ 
INSERT INTO STUDENT_TBL (STUDENT_ID, 
             STUDENT_NAME, 
             STUDENT_SEX, 
             STUDENT_BIRTHDAY, 
             CLASS_ID) 
 VALUES  (123456, 
      '某某某', 
      '女', 
      '1980-08-01', 
      121546 
      )

Create the configuration file mysql.properties used to connect to MySql.


jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost:3306/student_manager?user=root&password=bjpowernode&useUnicode=true&characterEncoding=UTF-8

Build MyBatis environment

The order is arbitrary, the current order is Because you can modify the written files as little as possible.

Create entity class: StudentEntity


##

public class StudentEntity implements Serializable { 
  private static final long serialVersionUID = 3096154202413606831L; 
  private ClassEntity classEntity; 
  private Date studentBirthday; 
  private String studentID; 
  private String studentName; 
  private String studentSex; 
   
  public ClassEntity getClassEntity() { 
    return classEntity; 
  } 
 
  public Date getStudentBirthday() { 
    return studentBirthday; 
  } 
 
  public String getStudentID() { 
    return studentID; 
  } 
 
  public String getStudentName() { 
    return studentName; 
  } 
 
  public String getStudentSex() { 
    return studentSex; 
  } 
 
  public void setClassEntity(ClassEntity classEntity) { 
    this.classEntity = classEntity; 
  } 
 
  public void setStudentBirthday(Date studentBirthday) { 
    this.studentBirthday = studentBirthday; 
  } 
 
  public void setStudentID(String studentID) { 
    this.studentID = studentID; 
  } 
 
  public void setStudentName(String studentName) { 
    this.studentName = studentName; 
  } 
 
  public void setStudentSex(String studentSex) { 
    this.studentSex = studentSex; 
  } 
}

Create data access interface

Dao interface corresponding to the Student class: StudentMapper.



public interface StudentMapper { 
   
  public StudentEntity getStudent(String studentID); 
   
  public StudentEntity getStudentAndClass(String studentID); 
   
  public List<StudentEntity> getStudentAll(); 
   
  public void insertStudent(StudentEntity entity); 
   
  public void deleteStudent(StudentEntity entity); 
   
  public void updateStudent(StudentEntity entity); 
}

Create SQL mapping statement file

Student class sql statement file StudentMapper.xml


resultMap tag: mapping of table fields and attributes.


Select tag: query sql.



<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 
<mapper namespace="com.manager.data.StudentMapper"> 
 
  <resultMap type="StudentEntity" id="studentResultMap"> 
    <id property="studentID" column="STUDENT_ID"/> 
    <result property="studentName" column="STUDENT_NAME"/> 
    <result property="studentSex" column="STUDENT_SEX"/> 
    <result property="studentBirthday" column="STUDENT_BIRTHDAY"/> 
  </resultMap> 
   
  <!-- 查询学生,根据id --> 
  <select id="getStudent" parameterType="String" resultType="StudentEntity" resultMap="studentResultMap"> 
    <![CDATA[ 
      SELECT * from STUDENT_TBL ST 
        WHERE ST.STUDENT_ID = #{studentID} 
    ]]>  
  </select> 
   
  <!-- 查询学生列表 --> 
  <select id="getStudentAll" resultType="commanagerdatamodelStudentEntity" resultMap="studentResultMap"> 
    <![CDATA[ 
      SELECT * from STUDENT_TBL 
    ]]>  
  </select> 
   
</mapper>

Create MyBatis mapper configuration file

Create MyBatis configuration in src/main/resource File: mybatis-config.xml.


typeAliases tag: Give the class an alias. com.manager.data.model.StudentEntity class, you can use StudentEntity instead.


Mappers tag: Load the SQL mapping statement file of the entity class in MyBatis.


<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> 
<configuration> 
  <typeAliases> 
    <typeAlias alias="StudentEntity" type="com.manager.data.model.StudentEntity"/> 
  </typeAliases> 
  <mappers> 
    <mapper resource="com/manager/data/maps/StudentMapper.xml" /> 
  </mappers> 
</configuration>

Modify the Spring configuration file

The main thing is to add the bean of the SqlSession production factory class: SqlSessionFactoryBean, ( in the mybatis.spring package). The configuration file location and dataSource need to be specified.


The implementation bean corresponding to the data access interface. Created through MapperFactoryBean. It is necessary to implement the full name of the interface class and a reference to the SqlSession factory bean.



<!-- 导入属性配置文件 --> 
<context:property-placeholder location="classpath:mysql.properties" /> 
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
  <property name="driverClassName" value="${jdbc.driverClassName}" /> 
  <property name="url" value="${jdbc.url}" /> 
</bean> 
 
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
  <property name="dataSource" ref="dataSource" /> 
</bean> 
 
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
  <property name="configLocation" value="classpath:mybatis-config.xml" /> 
  <property name="dataSource" ref="dataSource" /> 
</bean> 
 
<!— mapper bean --> 
<bean id="studentMapper" class="org.mybatis.spring.MapperFactoryBean"> 
  <property name="mapperInterface" value="com.manager.data.StudentMapper" /> 
  <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
</bean>

You can also not define the mapper bean and use annotations:


Add StudentMapper to the annotations


@Repository 
@Transactional 
public interface StudentMapper { 
}

Correspondingly, scanning needs to be added to dispatcher-servlet.xml:



<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 
  <property name="annotationClass" value="org.springframework.stereotype.Repository"/> 
  <property name="basePackage" value="comlimingmanager"/> 
  <property name="sqlSessionFactory" ref="sqlSessionFactory"/> 
</bean>

Test StudentMapper

Use SpringMVC to test, create a TestController, configure tomcat, access the index.do page for testing:



@Controller 
public class TestController { 
 
  @Autowired 
  private StudentMapper studentMapper; 
   
  @RequestMapping(value = "index.do") 
  public void indexPage() {   
    StudentEntity entity = studentMappergetStudent("10000013"); 
    System.out.println("name:" + entity.getStudentName()); 
  }   
}

Use Junit to test:



@RunWith(value = SpringJUnit4ClassRunner.class) 
@ContextConfiguration(value = "test-servletxml") 
public class StudentMapperTest { 
   
  @Autowired 
  private ClassMapper classMapper; 
   
  @Autowired 
  private StudentMapper studentMapper; 
   
  @Transactional 
  public void getStudentTest(){ 
    StudentEntity entity = studentMapper.getStudent("10000013"); 
    System.out.println("" + entity.getStudentID() + entity.getStudentName()); 
     
    List<StudentEntity> studentList = studentMapper.getStudentAll(); 
    for( StudentEntity entityTemp : studentList){ 
      System.out.println(entityTemp.getStudentName()); 
    } 
  } 
}

The above is the detailed content of Introduction and configuration details of mybatis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn