简体   繁体   English

Mybatis 插入自定义对象

[英]Mybatis insert custom object

In almost all example i found for mybatis, people specify every column for insertion.I dont want to specify each and every column in the table.在我为 mybatis 找到的几乎所有示例中,人们指定要插入的每一列。我不想指定表中的每一列。 Is there any way that, when i call addProfile() with user object.有什么办法可以,当我用用户对象调用 addProfile() 时。 All the properties mapped and inserted directly into all the columns of the given table ?所有属性映射并直接插入到给定表的所有列中? I want it this way...我想要这样...

@Insert("insert into user values #{user}")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
public int addProfile(User user);

You can pass the User object as a parameter in your addProfile() method.您可以在addProfile()方法中将 User 对象作为参数传递。 But the String you specify inside the @Insert annotation is a plain SQL statement it does not know the user object you pass into the statement.但是您在@Insert注释中指定的 String 是一个普通的 SQL 语句,它不知道您传递给该语句的用户对象。

This answer points it clearly,这个回答明确指出,

MyBatis has auto mapping when reading data from database but doesn't have option to automatically map fields on insertion. MyBatis 在从数据库读取数据时有自动映射,但没有选项在插入时自动映射字段。

It is possible to have implicit fields in SQL select statement ( select * from table ) so there is automatic mapping to POJO in this case but it is not possible to have implicit fields in update or insert hence no auto-mapping. SQL select 语句( select * from table )中可能有隐式字段,因此在这种情况下会自动映射到 POJO,但在更新或插入中不可能有隐式字段,因此没有自动映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM