The previous chapter Mybatis introduction overview and the first Mybatis instance to achieve add, delete, change, check, has built eclipse, Mybatis,mysql environment, and achieve a simple query. Note that this approach uses the SqlSession instance to execute the mapped SQL statement directly:

? 1 session.selectOne(“com.mucfc.model.EmployeerMapper.findEmployeerByID”, 1); There is a simpler way, and a better way, to use interfaces that properly describe parameters and the return values of SQL statements (such as EmployeerMapper.java), so that you can now have simpler, safer code that doesn’t have string literals and conversion bugs that are easy to happen. Here is the detailed process:

This article will be changed to interface class to achieve add, delete, change and check

The whole project catalog:

The sample project for this article is free to download

Mybatis configuration file mybatis-config.xml

br > PUBLIC “- / / mybatis.org//DTD Config / 3.0 / EN” “http://mybatis.org/dtd/mybatis-3-config.dtd” >


<! The -- element allows a property-format counterpart file to be provided in addition to the main profile, making the master profile more generic. This is useful for deployment --> <properties resource="mysql.properties" /> <! -- Set alias, Must be placed under the properties - > < typeAliases > < typeAlias alias = "Employeer" type = "com. Mucfc. Model. The Employeer" / > < / typeAliases > <! > <environment id="development"> <transactionManager type="JDBC" />  <dataSource type="POOLED"> <! -- <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test? characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="christmas258@"/> --> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <! - list the mapping file - > < mappers > < mapper resource = "com/mucfc/model/Employeer. XML" / > < / mappers >Copy the code

The mysql configuration file. The properties driver = com. Mysql.. JDBC driver url = JDBC: mysql: / / localhost: 3306 / test? charset=utf8 username=root password=christmas258@

2. The data table belongs to the employeer. JAVA class

package com.mucfc.model;

import java.io.Serializable;

/ * *

  • Employee information *@author Linbingwen

*/ public class Employeer {

private Integer employeer_id;
private String employeer_name;
private Integer employeer_age ;
private String employeer_department;
private String employeer_worktype;
 
public Employeer() {
    super();
}
public Integer getEmployeer_id() {
    return employeer_id;
}
public void setEmployeer_id(Integer employeer_id) {
    this.employeer_id = employeer_id;
}
public String getEmployeer_name() {
    return employeer_name;
}
public void setEmployeer_name(String employeer_name) {
    this.employeer_name = employeer_name;
}
public Integer getEmployeer_age() {
    return employeer_age;
}
public void setEmployeer_age(Integer employeer_age) {
    this.employeer_age = employeer_age;
}
public String getEmployeer_department() {
    return employeer_department;
}
public void setEmployeer_department(String employeer_department) {
    this.employeer_department = employeer_department;
}
public String getEmployeer_worktype() {
    return employeer_worktype;
}
public void setEmployeer_worktype(String employeer_worktype) {
    this.employeer_worktype = employeer_worktype;
}
@Override
public String toString() {
    return "Employeer [employeer_id=" + employeer_id + ", employeer_name="
            + employeer_name + ", employeer_age=" + employeer_age
            + ", employeer_department=" + employeer_department
            + ", employeer_worktype=" + employeer_worktype + "]";
}
 
Copy the code

} Then the configuration of the SQL statement employeer.xml:

br>”http://mybatis.org/dtd/mybatis-3-mapper.dtd”>

<! ParameterType ="int" resultType="Employeer"> select* from 't_employeer' WHERE (select ID ="findEmployeerByID" parameterType="int" resultType="Employeer"> select* from 't_employeer' WHERE (select id="findEmployeerByID" parameterType=" Employeer" employeer_id =#{employeer_id} </select> <! -- Insert --> <! -- useGeneratedKeys set to "true" to MyBatis to obtain the primary key automatically generated by the database; KeyProperty ="id" specifies to inject the obtained primary key value into the Employeer ID attribute --> <insert ID ="addEmployeer" parameterType="Employeer" useGeneratedKeys="true" keyProperty="employeer_id"> insert into `t_employeer`(employeer_name,employeer_age,employeer_department,employeer_worktype) values(#{employeer_name},#{employeer_age},#{employeer_department},#{employeer_worktype}) </insert> <! ParameterType ="int"> delete from 't_employeer' where employeer_id = #{employeer_id} </delete> <! -- Modify --> <update ID ="updateEmployeer" parameterType="Employeer"> update t_employeer set employeer_name = #{employeer_name},employeer_age= #{employeer_age},employeer_department = #{employeer_department} ,employeer_worktype=#{employeer_worktype} where employeer_id = #{employeer_id} </update>Copy the code


?

1

Note com. Mucfc. Mapper. EmployeerMapper this class exists, it is an interface class, a speaking we are using com. Mucfc. Model. EmployeerMapper, and on this class is not exist

4. SQL statement mapping class Employeermapper. Java

package com.mucfc.mapper;

import com.mucfc.model.Employeer;

/ * *

  • SQL statement mapping classes
  • @author linbingwen
  • @ time 2015.5.11 * /

public interface EmployeerMapper {

XML method name. */ public Employeer findEmployeerByID(int ID); XML method name. */ public void addEmployeer(Employeer Employeer); XML method name. */ public void deleteEmployeer(int ID); XML method name. */ public void updateEmployeer(Employeer Employeer);Copy the code

} 5, test:

(1) Add commands

Mybatis = Mybatis = Mybatis = Mybatis

/ * *

  • Increase the * /

public static void addEmployeer(Employeer employeer){

SqlSession session = null; try { session = sqlSessionFactory.openSession(); / / the return value is the article records the number of int resultCount = session. The insert (" com. Mucfc. Model. EmployeerMapper. AddEmployeer ", employeer); System.out.printf(" Currently inserted employeer_id :%d Number of currently inserted employeer_id :%d ", employeer.getemployeer_id (),resultCount); // Get the id of the inserted object system.out.println (""); session.commit() ; } finally { session.close(); }Copy the code

}

Change to interface programming:

/ * *

  • Increase the * /

public static void addEmployeer(Employeer employeer){

SqlSession session = null;
try {
    session = sqlSessionFactory.openSession();
    EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
    employeerMapper.addEmployeer(employeer);
    session.commit() ;          
} finally {
    session.close();
}
 Copy the code

}

(2) Delete command

Mybatis = Mybatis = Mybatis = Mybatis

/ * *

  • delete
  • * /

public static void deleteEmployeer(int id){

SqlSession session = null; try { session = sqlSessionFactory.openSession(); / / the return value is the article records the number of int resultCount = session. Delete (" com. Mucfc. Model. EmployeerMapper. DeleteEmployeer ", id); System.out.println(" resultCount); Session.mit (); } finally { session.close(); }Copy the code

}

Change to interface programming:

/ * *

  • delete
  • * /

public static void deleteEmployeer(int id){

SqlSession session = null;
try {
    session = sqlSessionFactory.openSession();
    EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
    employeerMapper.deleteEmployeer(id);
    session.commit() ;          
} finally {
    session.close();
}Copy the code

}

(3) Search command

Mybatis = Mybatis = Mybatis = Mybatis

/ * *

  • To find the * /

public static void findEmployeerById(int id) {

SqlSession session = null;
try {
    session = sqlSessionFactory.openSession();
    Employeer employeer = (Employeer) session.selectOne(
            "com.mucfc.model.EmployeerMapper.findEmployeerByID", 1);
    if (employeer == null)
        System.out.println("null");
    else
        System.out.println(employeer);
} finally {
    session.close();
}Copy the code

}

Change to interface programming:

/ * *

Public static void findEmployeerById(int ID) {SqlSession Session = null; try { session = sqlSessionFactory.openSession(); EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class); Employeer employeer=employeerMapper.findEmployeerByID(id); if (employeer == null) System.out.println("null"); else System.out.println(employeer); } finally { session.close(); }}Copy the code

(4) Modify the command

Mybatis = Mybatis = Mybatis = Mybatis = Mybatis = Mybatis = Mybatis

  • Change the * /

public static void updateEmployeer(Employeer employeer){

SqlSession session = null;
try {
    session = sqlSessionFactory.openSession(); 
    session.update("com.mucfc.model.EmployeerMapper.updateEmployeer",employeer);    
    session.commit() ;          
} finally {
    session.close();
}
 Copy the code

}

Change to interface programming:

/ * *

  • Change the * /

public static void updateEmployeer(Employeer employeer){

SqlSession session = null;
try {
    session = sqlSessionFactory.openSession(); 
    EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
    employeerMapper.updateEmployeer(employeer);
    session.commit() ;          
} finally {
    session.close();
}
 Copy the code

}

Here’s the full test:

package com.mucfc.test;

import java.io.IOException;

import java.io.Reader;

import org.apache.ibatis.io.Resources;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.mucfc.mapper.EmployeerMapper;

import com.mucfc.model.Employeer;

public class MybatisTest {

private static SqlSessionFactory sqlSessionFactory; private static Reader reader; static { try { reader = Resources.getResourceAsReader("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (Exception e) { e.printStackTrace(); Public static void findEmployeerById(int ID) {SqlSession session = null; try { session = sqlSessionFactory.openSession(); EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class); Employeer employeer=employeerMapper.findEmployeerByID(id); if (employeer == null) System.out.println("null"); else System.out.println(employeer); } finally { session.close(); }} /** * add */ public static void addEmployeer(Employeer Employeer){SqlSession session = null; try { session = sqlSessionFactory.openSession(); EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class); employeerMapper.addEmployeer(employeer); session.commit() ; } finally { session.close(); } /** * delete ** / public static void deleteEmployeer(int ID){SqlSession session = null; try { session = sqlSessionFactory.openSession(); EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class); employeerMapper.deleteEmployeer(id); session.commit() ; } finally { session.close(); } /** * Change */ public static void updateEmployeer(Employeer Employeer){SqlSession session = null; try { session = sqlSessionFactory.openSession(); EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class); employeerMapper.updateEmployeer(employeer); session.commit() ; } finally { session.close(); } } public static void main(String[] args) { Employeer employeer1=new Employeer(); Employeer1. SetEmployeer_name (" li si "); employeer1.setEmployeer_age(23); Employeer1. setEmployeer_department(" Product part "); Employeer1.setemployeer_worktype (" Development Engineer "); Employeer employeer2=new Employeer(); Employeer2. SetEmployeer_name (" zhang "); employeer2.setEmployeer_age(30); Employeer2. SetEmployeer_department (" Product Part 2 "); Employeer2.setemployeer_worktype (" Test Engineer "); Employeer employeer3=new Employeer(); Employeer3. SetEmployeer_name (" wang "); employeer3.setEmployeer_age(22); Employeer3. SetEmployeer_department (" Three products "); Employeer3. SetEmployeer_worktype (" data analyst "); Employeer employeer4=new Employeer(); Employeer4. SetEmployeer_name (" Ming Ming "); employeer4.setEmployeer_age(22); Employeer4. SetEmployeer_department (" Accounting "); Employeer4. SetEmployeer_worktype (" Financial staff "); / / insert addEmployeer (employeer1); addEmployeer(employeer2); addEmployeer(employeer3); addEmployeer(employeer4); findEmployeerById(26); deleteEmployeer(27); / / change employeer2. SetEmployeer_id (28); employeer2.setEmployeer_age(21); Employeer2. SetEmployeer_department (" Product four "); updateEmployeer(employeer2); }Copy the code

}

Test results:

Four data ids 25 to 28 are inserted

And then number 27 was deleted

29 was modified