实体类参数自动赋值

实体类参数自动赋值

前言

日常开发我们会遇到一个问题,在返回实体类时,时间格式是Date类型,但是接口开发时前端往往需要的是String类型,这时候如果使用相对原生的方式可以在服务层进行转换,加上使用@Transient注解去绑定一些不与数据库绑定的属性去携带参数,但是在使用JPA自带的分页,或者一些结果集封装的形式进行传参时,就无法进行数据转换赋值,这时候就可以通过改变属性的get方法去设置参数

代码

package com.yiyun.member.entity;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.GenericGenerator;


@Entity
@Table(name = "commodity")
@DynamicInsert
@NamedQuery(name = "Commodity.findAll", query = "SELECT s FROM Commodity s")
public class Commodity implements Serializable {

	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long id;
	
	@Column(name = "create_time")
    private Date createTime;
	
	@Column(name = "open_time")
    private Date openTime;
	
	@Column(name = "over_time")
    private Date overTime;
    
	@Transient
	private String overTimeStr;
	
	@Transient
	private String openTimeStr;
	
	@Transient
	private String createTimeStr;

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public Date getOpenTime() {
		return openTime;
	}

	public void setOpenTime(Date openTime) {
		this.openTime = openTime;
	}

	public Date getOverTime() {
		return overTime;
	}

	public void setOverTime(Date overTime) {
		this.overTime = overTime;
	}
	//初始化赋值
	public String getOverTimeStr() {
		return overTimeStr = overTime==null?"":new SimpleDateFormat("yyyy-MM-dd HH:mm").format(overTime);
	}

	public void setOverTimeStr(String overTimeStr) {
		this.overTimeStr =overTimeStr;
	}

	public String getOpenTimeStr() {
		return openTimeStr = openTime == null?"":new SimpleDateFormat("yyyy-MM-dd HH:mm").format(openTime);
	}

	public void setOpenTimeStr(String openTimeStr) {
		this.openTimeStr = openTimeStr;
	}

	public String getCreateTimeStr() {
		return createTimeStr = createTime == null?"":new SimpleDateFormat("yyyy-MM-dd HH:mm").format(createTime);
	}

	public void setCreateTimeStr(String createTimeStr) {
		this.createTimeStr = createTimeStr;
	}
	
}

这里代码return createTimeStr = createTime == null?"":new SimpleDateFormat(“yyyy-MM-dd HH:mm”).format(createTime); 方式去赋值,通过三元运算符去赋值,将实体类其他的参数赋值给自己。

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页