MyBatis resolving attribute names inconsistent with field names

Source: Internet
Author: User

In the development of the situation should be encountered, the database field names and property names are inconsistent, usually the database in the name of the field between multiple words using underscores concatenated together, and in the class property names are mostly used to name the hump, I have seen most of the way, So what if we use MyBatis to solve this problem? As follows:

Data sheet:

CREATE TABLE tab_department (IDs int PRIMARY KEY auto_increment,de_name VARCHAR () COMMENT ' Department name ', P_ids INT COMMENT ' parent Department I d ', De_charge_person VARCHAR (COMMENT ' department head ', Create_time long COMMENT ' creation time ') COMMENT ' departmental table '

Entity class:

Package com.tenghu.mybatis.model;import java.io.serializable;/** * Departmental table * @author Arvin_li * */public class Department Impl Ements serializable{private static final long serialversionuid = 6998332095922284289l;private int ids;//Department number private String dename;//department name private INT pids;//Parent Department idprivate String dechargeperson;//department head private long createtime;//creation time// Omit get and Set methods}


MyBatis Master configuration file:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configurationpublic "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration><!--Configure entity class name--><typealiases><typealias type= " Com.tenghu.mybatis.model.Department "alias=" Department "/></typealiases><environments default=" Development "><environment id=" development "><transactionmanager type=" JDBC "/><dataSource type=" Pooled "><property name=" Driver "value=" ${jdbc.driver} "/><property name=" url "value=" ${jdbc.url} "/> <property name= "username" value= "${jdbc.username}"/><property name= "password" value= "${jdbc.password}"/ ></dataSource></environment></environments><!--Configuring the mapping file--><mappers><mapper Resource= "Com/tenghu/mybatis/model/xml/departmentmapper.xml"/></mappers></configuration>

Map file:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE mapperpublic "-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >< Mapper namespace= "Com.tenghu.mybatis.model.xml.DepartmentMapper" ><!--configuration map field--><resultmap type= " Department "id=" tab_department "><id property=" IDs "column=" IDs "/><result property=" Dename "column=" De_ Name "/><result property=" PIds "column=" P_ids "/><result property=" Dechargeperson "column=" De_charge_ Person "/><result property=" Createtime "column=" create_time "/></resultmap><!--query all departments-->< Select Id= "queryalldepartment" resultmap= "tab_department" >select * from Tab_department</select></mapper >

Tool class:

Package Com.tenghu.mybatis.util;import Java.io.ioexception;import Java.io.inputstream;import java.util.Properties; Import Org.apache.ibatis.io.resources;import Org.apache.ibatis.session.sqlsession;import Org.apache.ibatis.session.sqlsessionfactory;import org.apache.ibatis.session.sqlsessionfactorybuilder;/** * MyBatis Tool class * @author Arvin_li * @version 1.0 * */public class Mybatisutil {private Mybatisutil () {}//Declaration sqlsession Factory Private Static Sqlsessionfactory sqlsessionfactory;//get Sqlsession factory static{try {//Get MyBatis Master profile stream InputStream Inputstream=resources.getresourceasstream ("Mybatis-config.xml");//Create Property file Object Properties Properties=new properties () ;//Load Property profile Properties.load (Resources.getresourceasstream ("jdbc.properties"));// Create a Sqlsessionfactory object Sqlsessionfactory=new sqlsessionfactorybuilder (). Build (InputStream, properties);} catch (IOException e) {e.printstacktrace ();}} /** * Open Sqlsession object, not automatically submit * @return */public static sqlsession opensession () {return sqlsessionfactory.opensession ();} /** * Turn on autocommit sqlsession * @return */public static sqlsession openautocommitsession () {return sqlsessionfactory.opensession ( true);} /** * Close sqlsession * @param sqlsession */public static void CloseSession (Sqlsession sqlsession) {if (null!=sqlsession) { Sqlsession.close ();} Sqlsession=null;}}

Test class:

Package Com.tenghu.mybatis.test;import Java.util.list;import Org.apache.ibatis.session.sqlsession;import Org.junit.test;import Com.tenghu.mybatis.model.department;import com.tenghu.mybatis.util.mybatisutil;/** * Division Test class * @ Author Arvin_li * */public class Departmenttest {//namespace private String namespace= " Com.tenghu.mybatis.model.xml.DepartmentMapper. "; * * Check out ALL departments */@Testpublic void testqueryalldepartment () {//Get sqlsessionsqlsession sqlsession=mybatisutil.opensession (); try {//Query list<department> departlist=sqlsession.selectlist (namespace+ "queryalldepartment");//Output Department information for ( Department department:departlist) {System.out.println (Department.getids () + "\ T" +department.getdename () + "\ T" + Department.getpids () + "\ T" +department.getdechargeperson ());}} catch (Exception e) {e.printstacktrace ();} finally{//Close Sqlsessionmybatisutil.closesession (sqlsession);}}

This allows you to handle inconsistencies in field names and property names.




MyBatis resolving attribute names inconsistent with field names

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.