解决mybatis实体类和数据库列名不匹配的两种办法
我们在实际开发中,会遇到实体类与数据库类不匹配的情况,在开发中就会产生各种各样的错误,那么我们应该怎么去解决这一类的错误呢?很简单,下面我们介绍两种解决方法:
首先我们看一下数据库和实体类不匹配的情况:

解决办法1
当我们查询的时候我们可以在映射文件mapper.xml中采取取别名的方式:
<select id="findAll" resultMap="cn.com.scitc.domian.User" >
select id as userId,username as userName,birthday as userBirthday,sex as userSex,address as userAddress from user
</select>
<!--配置查询所有-->
<select id="findAll" resultType="cn.com.scitc.domian.User" >
-- select id as userId,username as userName,birthday as userBirthday,sex as userSex,address as userAddress from user
select * from user;
</select>
<!--save-->
<insert id="saveUser" parameterType="cn.com.scitc.domian.User">
<!-- 配置插入操作后,获取插入数据的id keyProperty实体类 keyColum是数据库的值 order什么时候操作-->
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER" >
select last_insert_id()
</selectKey>
insert into user (username,birthday,sex,address) values (#{userName},#{userBirthday},#{userSex},#{userAddress});
</insert>
<!--update-->
<update id="updateUser" parameterType="cn.com.scitc.domian.User">
update user set username = #{userName},birthday=#{userBirthday},sex=#{userSex},address=#{userAddress} where id=#{id}
</update>
<!--delete-->
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
</delete>
<!--用id 查询一个 交代清楚返回的结果-->
<select id="findById" parameterType="Integer" resultType="cn.com.scitc.domian.User">
select * from user where id = #{userId}
</select>
<!--username模糊查询-->
<select id="fingByName" parameterType="string" resultType="cn.com.scitc.domian.User">
select * from user where username like #{userName}
</select>
我们再看看接口和测试类
接口dao中
public interface UserDao {
// 查询所有
// @Select("select * from user")
List<User> findAll();
// save
void saveUser(User user);
// update
void updateUser(User user);
// delete
void deleteUser(Integer userId);
// 查询一个
User findById(Integer userId);
// 根据名称 模糊查询
List<User> fingByName(String username);
}
实现类:
public class MybatisTest {
// 初始化值
private InputStream in;
private SqlSession sqlSession;
private UserDao userDao;
// 在测试方法执行之前执行
@Before
public void init() throws Exception{
// 读取文件
in = Resources.getResourceAsStream("mybatis-Config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
sqlSession = factory.openSession();
userDao = sqlSession.getMapper(UserDao.class);
}
@After
public void destory() throws Exception{
// 提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();;
in.close();
}
@Test
public void testFindAll() throws Exception{
List<User> users = userDao.findAll();
for (User user : users){
System.out.println("对象有:"+user);
}
}
// saveTest
@Test
public void TestSave() {
User user = new User();
user.setUserName("modify 修改");
user.setUserBirthday(new Date());
System.out.println("保存方法之前"+user);
user.setUserSex("男");
user.setUserAddress("天津");
userDao.saveUser(user);
System.out.println("保存方法之后"+user);
}
// update
@Test
public void TestUpdate() {
User user = new User();
user.setUserId(5);
user.setUserName("aa");
user.setUserBirthday(new Date());
user.setUserSex("男");
user.setUserAddress("德阳");
userDao.updateUser(user);
}
@Test
public void TestDelete(){
userDao.deleteUser(5);
}
// findById
@Test
public void findById(){
User user = userDao.findById(3);
System.out.println(user);
}
//username模糊查询
@Test
public void TestFindByName(){
List<User> users = userDao.fingByName("%李%");
// List<User> users = userDao.fingByName("李四");
for (User user:users){
System.out.println(user);
}
}
//查询总记录数
@Test
public void findTotal(){
int count = userDao.findTotal();
System.out.println(count);
}
//username模糊查询
@Test
public void TestQuery(){
QueryVo queryVo = new QueryVo();
User user = new User();
user.setUserName("%李%");
queryVo.setUser(user);
List<User> userByVo = userDao.findUserByVo(queryVo);
for (User u:userByVo){
System.out.println(u);
}
}
}
解决办法2
配置查询结果的列名和实体类的属性名对应的关系
依然是映射文件
<!--配置查询结果的列名 和实体类的属性名对应的关系-->
<resultMap id="userMap" type="cn.com.scitc.domian.User">
<!--主键字段对应名-->
<id property="userId" column="id"></id>
<!--非主键字段的对应 property是实体类严格区分大小写 column数据库字段严格按照数据库字段 -->
<result property="userName" column="username"></result>
<result property="userBirthday" column="birthday"></result>
<result property="userSex" column="sex"></result>
<result property="userAddress" column="address"></result>
</resultMap>
我们在mapper.xml文件中配置这些配置的作用就是与数据库进行关联:
=注意
主键 :实体类的主键id一定要和数据库的主键id写对
property:是实体类严格区分大小写
column数据库字段严格按照数据库字段
配置好这些 我们就开始引用。
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace dao权限类名===别名-->
<mapper namespace="cn.com.scitc.dao.UserDao">
<!--配置查询结果的列名 和实体类的属性名对应的关系-->
<resultMap id="userMap" type="cn.com.scitc.domian.User">
<!--主键字段对应名-->
<id property="userId" column="id"></id>
<!--非主键字段的对应 property是实体类严格区分大小写 column数据库字段严格按照数据库字段 -->
<result property="userName" column="username"></result>
<result property="userBirthday" column="birthday"></result>
<result property="userSex" column="sex"></result>
<result property="userAddress" column="address"></result>
</resultMap>
<!--配置查询所有-->
<select id="findAll" resultType="userMap" >
-- select id as userId,username as userName,birthday as userBirthday,sex as userSex,address as userAddress from user
select * from user;
</select>
<!--save-->
<insert id="saveUser" parameterType="userMap">
<!-- 配置插入操作后,获取插入数据的id keyProperty实体类 keyColum是数据库的值 order什么时候操作-->
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER" >
select last_insert_id()
</selectKey>
insert into user (username,birthday,sex,address) values (#{userName},#{userBirthday},#{userSex},#{userAddress});
</insert>
<!--update-->
<update id="updateUser" parameterType="userMap">
update user set username = #{userName},birthday=#{userBirthday},sex=#{userSex},address=#{userAddress} where id=#{id}
</update>
<!--delete-->
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
</delete>
<!--用id 查询一个 交代清楚返回的结果-->
<select id="findById" parameterType="Integer" resultType="userMap">
select * from user where id = #{userId}
</select>
<!--username模糊查询-->
<select id="fingByName" parameterType="string" resultType="userMap">
select * from user where username like #{userName}
</select>
<!--username模糊查询 第二种写法-->
<!--<select id="fingByName" parameterType="string" resultType="cn.com.scitc.domian.User">-->
<!--select *from user where username like '%${value}%'-->
<!--</select>-->
<!--获取用户总记录条数-->
<select id="findTotal" resultType="int">
select count(id) from user
</select>
<!--根据queryVo的条件查询用户-->
<select id="findUserByVo" parameterType="cn.com.scitc.domian.QueryVo" resultType="UserMap">
select * from user where username like #{user.userName}
</select>
</mapper>
就是相当于把每一个要执行的sql语句的resultType的参数换成resultMap的值。
最后在进行测试就OK.。
解决mybatis实体类和数据库列名不匹配的两种办法的更多相关文章
- 阶段3 1.Mybatis_05.使用Mybatis完成CRUD_9 Mybatis中的返回值深入-解决实体类属性和数据库列名不对应的两种方式
sql语句里面起别名的方式 测试查询的方法 数据字段 都有值了. 配置查询接口列表和实体类属性名对应关系 id可以随便起名 主键的对应 再次测试,并没有封装成功 这是应为定义的对应关系并没有使用. 当 ...
- 实体类与数据库字段不匹配问题,java.sql.SQLSyntaxErrorException: Unknown column 'xxx' in 'field list'
控制台报错 ### Error querying database. Cause: java.sql.SQLSyntaxErrorException: Unknown column 'user_nam ...
- MyBatis系列二 之 数据库列名于程序实体类中字段名称不一致
MyBatis系列二 之 数据库列名于程序实体类中字段名称不一致 情景:当数据库中的列名与我们程序实体类中的字段名称不一致 使用ResultMap节点配置信息 在映射文件中 ...
- 解决SpringDataJpa实体类中属性顺序与数据库中生成字段顺序不一致的问题
一.在application.yml配置中添加数据库根据实体类自动创建数据库表的配置(这里数据库采用MySQL数据库) jpa: database: MYSQL show-sql: true #Hib ...
- 在Code First中使用Migrations对实体类和数据库做出变更
在Code First中使用Migrations对实体类和数据库做出变更,Mirgration包含一系列命令. 工具--库程序包管理器--程序包管理器控制台 运行命令:Enable-Migration ...
- ASP.NET Core EFCore 之DBFirst 自动创建实体类和数据库上下文
通过引用Nuget包添加实体类 运行 Install-Package Microsoft.EntityFrameworkCore.SqlServer 运行 Install-Package Micros ...
- Oracle数据库日期范围查询的两种实现方式
参考文档:http://database.51cto.com/art/201108/288058.htm Oracle数据库日期范围查询有两种方式:to_char方式和to_date方式,接下来我们通 ...
- Mybatis实体类属性与数据库字段不一致解决办法
例如:实体类 String userName 数据库:name 解决办法一: 通过给字段加别名,别名写成实体类属性一 eg:select name userName from student ...
- Mybatis——实体类属性名和数据库字段名不同时的解决方案
数据库的字段: 对应的实体类: 方案一: 在XML映射文件中使用的resultMap,优点:可以被重复使用. <resultMap id="BaseResultMap" ty ...
随机推荐
- LeetCode_401. Binary Watch
401. Binary Watch Easy A binary watch has 4 LEDs on the top which represent the hours (0-11), and th ...
- 【Leetcode_easy】844. Backspace String Compare
problem 844. Backspace String Compare solution1: class Solution { public: bool backspaceCompare(stri ...
- 【原生JS插件】LoadingBar页面顶部加载进度条
先展示一下已经实现的效果: 预览地址:http://dtdxrk.github.io/js-plug/LoadingBar/index.html 看到手机上的浏览器内置了页面的加载进度条,想用在pc上 ...
- vscode springboot logback 日志输出到不同文件
参照了:https://blog.csdn.net/appleyk/article/details/78717388# 在src\main\resources中新建一个logback-boot.xml ...
- consui(二)集群配置
consul集群搭建:一.软件安装Linux 环境下载zip包然后直接解压,然后把解压的文mv consul /bin检验安装是否成功,查看版本[root@node1 ~]consul -vConsu ...
- nodejs ffi 调用dll
安装依赖 npm install --global --production windows-build-tools(在管理员权限打开的命令行中执行) npm install -g node-gyp ...
- Ubuntu 12.04下Matlab2009a启动后出现某些问题的解决方法
本文来自linux公社:http://www.linuxidc.com/Linux/2012-08/68346.htm 在Ubuntu 12.04 LTS下正确安装matlab r2009a后,启动起 ...
- [转帖]LINUX下使用rinetd端口转发
LINUX下使用rinetd端口转发 https://www.iteye.com/blog/lvinie-1167701 . 本来想自己写一下 发现没必要. 并且原作者提供了pan.baidu.com ...
- 20191031:Python取反运算详解
20191031:Python取反运算详解 取反运算:~3 == 4 1.对于数字 3 =======>转换为二进制表示为011 2.对011取反为100 3.为什么表示-4 a.计算机用补码表 ...
- 15. Scala并发编程模型Akka
15.1 Akka介绍 1) Akka是Java虚拟机JVM平台上构建高并发.分布式和容错应用的工具包和运行时,可以理解成Akka是编写并发程序的框架 2) Akka用Scala语言写成,同时提供了S ...