Home > Java > javaTutorial > How to deal with inconsistencies between database fields and attributes in entity beans in MyBatis

How to deal with inconsistencies between database fields and attributes in entity beans in MyBatis

Y2J
Release: 2018-05-18 17:10:18
Original
7354 people have browsed it

This article mainly introduces the method of adding, deleting, modifying and checking in getting started with MyBatis + how to deal with the inconsistency between database fields and entity fields. Friends in need can refer to the following

When the database fields and entity beans are propertiesWhen inconsistent

In the past, the Person name field in the database was name, and the attribute in PersonBean was also name, but later it was changed to user_name in the database,

Method 1: Starting from the field of the sql statement Alias, the alias is consistent with the object attributes in the entity

SELECT id,user_name as name,sex,age from person
<select id="find" resultType="com.luogg.domain.Person">
  SELECT id,user_name as name,sex,age from person
</select>
Copy after login

Method 2: The most powerful part of mybatis: reslutMap object

Add an intermediary reslutMap tag, and change the resultType in the select tag to resultMap, corresponding to the id of the resultMap tag.

Result set: resultType basic type, int, string, Person,

resultMap Exists for the intermediary tag resultMap.

<!--配置命名空间,命名空间+ .id 是唯一的sql语句标示符-->
<mapper namespace="com.luogg.mapper.PersonMapper">
 <!--中介,当数据库字段和实体bean对象属性不一致时,做一个对应关系-->
 <resultMap id="personRM" type="com.luogg.domain.Person">
  <!--主键映射-->
  <id property="id" column="ID"></id>
  <!--普通字段,property指实体属性,column结果集的字段名称,一致的字段可以不写-->
  <result property="name" column="USER_NAME"></result>
 </resultMap>
 <!--查询所有数据,参数有id,resultType结果集,parameterType参数-->
 <!--注意 : sql语句中如果有要填写集合的,比如查询所有数据,返回一个Person的结果集,那么resultType参数直接写 路径+集合的类型
  比如: 返回一个Person集合,那么就填写Person Bean所在的路径+Person-->
 <select id="find" resultMap="personRM">
  SELECT * from person
 </select>
 <!--通过ID查询数据,当有查询条件时,需要写parameterType,返回结果集仍然是Person, #{id}或者${id}都可以-->
 <select id="selById" parameterType="int" resultType="com.luogg.domain.Person">
  SELECT * FROM person WHERE id = #{id}
 </select>
</mapper>
Copy after login

Mybatis’s addition, deletion and modification check

Newly addedPersonnel information

First in PersonMapper Add insert tag in .xml, our database field user_name, Person entity attribute is name, which are inconsistent and different. Then write the code in TestMybatis.

<!--添加人员-->
 <insert id="insert" parameterType="com.luogg.domain.Person">
  INSERT INTO person(id,user_name,age,sex) VALUES(#{id},#{name},#{age},#{sex})
 </insert>
Copy after login

package test;

import com.luogg.domain.Person;
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 org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
 * Created by luogg on 2017/2/17.
 */
public class TestMybatis {
 //SqlSessionFactory为线程安全的
 private SqlSessionFactory factory;
 @Before
 public void init() throws IOException {
  String resource = "sqlMapConfig.xml";
  InputStream is = Resources.getResourceAsStream(resource);
  factory = new SqlSessionFactoryBuilder().build(is);
 }
 @Test //查询所有
 public void findAll() throws IOException {
  /**
   * 测试数据库的连接
   * 1.定义一个String类型的变量resource,指向刚才配置的连接数据库的xml文件
   * 2.创建一个输入流,来读取我们的数据库配置文件
   * 3.输入流创建工厂.
   * 4.有了工厂之后open工厂
   * 5.通过session访问配置文件中的sql语句
   */
  SqlSession session = factory.openSession();
  //如何访问PersonMapper.xml中的sql语句呢? 命名空间+ .id
  List<Person> list = session.selectList("com.luogg.mapper.PersonMapper.find");
  System.out.println(list.size());
  for(Person p : list){
   System.out.println(p);
  }
 }
 @Test //通过ID查询人员信息
 public void selById(){
  SqlSession session = factory.openSession();
  Person p = session.selectOne("com.luogg.mapper.PersonMapper.selById",1);
  System.out.println(p);
 }
 @Test //添加人员信息
 public void add(){
  SqlSession session = factory.openSession();
  Person p = new Person();
  p.setId(4);
  p.setName("luogg");
  p.setAge(22);
  p.setSex(1);
  int i = session.insert("com.luogg.mapper.PersonMapper.insert",p);
  session.commit();
  if(i==1){
   System.out.print("添加人员成功");
  }
 }
}
Copy after login

Modify personnel information and query the total number of records

prsonMapper.xml file

<!--修改成员信息-->
 <update id="update" parameterType="com.luogg.domain.Person">
  UPDATE person SET user_name=#{name},age=#{age} WHERE id=#{id}
 </update>
 <!--查询总的记录-->
 <select id="count" resultType="int">
  SELECT COUNT(*) FROM person
 </select>
Copy after login

TestMybatis.java file

@Test //修改人员信息
 public void updatePer(){
  SqlSession session = factory.openSession();
  Person p = new Person();
  p.setId(4);
  p.setName("luoggg");
  //p.setSex(1);
  p.setAge(23);
  int i = session.update("com.luogg.mapper.PersonMapper.update",p);
  session.commit();
  if(i==1){
   System.out.print("修改信息成功");
  }
 }
 @Test //查询总的记录条数
 public void selCount(){
  SqlSession session = factory.openSession();
  int i = session.selectOne("com.luogg.mapper.PersonMapper.count");
  System.out.println(i);
 }
Copy after login

Conditional query

Query based on conditions

<!--带条件查询-->
 <select id="selByL" parameterType="map" resultMap="personRM">
  SELECT <include refid="cols"/> FROM person
  where user_name like #{name}
  AND sex=#{sex}
 </select>
@Test //带条 件查询
 public void selByL(){
  SqlSession session = factory.openSession();
  Map<String,Object> map = new HashMap<String, Object>();
  map.put("name","luo%");
  map.put("sex",1);
  List<Person> list = session.selectList("com.luogg.mapper.PersonMapper.selByL",map);
  System.out.println(list.size());
  for(Person p : list){
   System.out.println(p);
  }
 }
Copy after login

[Related recommendations]

1. Special recommendations : "php Programmer Toolbox" V0.1 version download

2. Java Free Video Tutorial

3. JAVA Elementary Getting Started Video Tutorial

The above is the detailed content of How to deal with inconsistencies between database fields and attributes in entity beans in MyBatis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template