[英]Mapping a DB column name to a Bean property using annotations in Java Spring
the problem I am trying to solve is to map a DB column name to a bean property name in a Spring project. 我要解决的问题是在Spring项目中将数据库列名称映射到bean属性名称。 I cannot use JPA, or Hibernate.
我不能使用JPA或Hibernate。 Basically I want the db layer to know to write to the bean using the column mapping, but consumers of the bean to use the bean property name.
基本上,我希望db层知道使用列映射写入bean,但是bean的使用者要使用bean属性名。
A custom annotation might do it, but I am having a hard time finding documentation for what I want to do, which might mean thats its not a good idea. 自定义批注可以做到,但是我很难找到我想做的文档,这可能意味着这不是一个好主意。
A mapper of some sort might do it, but I like the idea of the annotation because then the mapping is documented in the bean. 某种映射器可以做到这一点,但是我喜欢注释的想法,因为这样映射就记录在了Bean中。
Given a bean: 给定一个bean:
public class ServiceBean
{
@ColumnMapping(value = "service_name")
private String serviceName;
@ColumnMapping(value = "service_desc")
private String serviceDesc;
public String getServiceName()
{
return serviceName;
}
public void setServiceName(String serviceName)
{
this.serviceName = serviceName;
}
public String getServiceDesc()
{
return serviceDesc;
}
public void setServiceDesc(String serviceDesc)
{
this.serviceDesc = serviceDesc;
}
}
I think the start of the annotation definition looks like this: 我认为注释定义的开始看起来像这样:
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ColumnMapping
{
String value();
}
I might be in the weeds here. 我可能在这里杂草丛生。
You could use MyBatis framework with following mapping configuration: 您可以将MyBatis框架与以下映射配置一起使用:
<resultMap id="MyResultMap" type="ServiceBean">
<result column="service_name" property="serviceName" javaType="String" />
<result column="service_desc" property="serviceDesc" javaType="String" />
</resultMap>
It is a lightweight SQL persistence and mapping framework that can be easily integrated in a Spring architecture. 它是一个轻量级的SQL持久性和映射框架,可以轻松地集成到Spring体系结构中。
The current version (v3) now supports annotations ( see here ). 当前版本(v3)现在支持注释( 请参阅此处 )。
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.