@Transient

[@Transient] 
  - 可选,表示该属性并非一个到数据库表的字段的映射,ORM 框架将忽略该属性,如果
    一个属性并非数据库表的字段映射,就务必将其标示为@Transient       否则 ORM 框架默认其注解为 @Basic
    该注解最好用在属性上 , 而不是方法上
    示例 :
    // 根据 birth 计算出 age 属性
    @Transient
    private int age;
    public int getAge(Date date){
        return new Date().getYear()- date.getYear() ;
    }  


package sun.rain.amazing.javax.anno.domain;

import lombok.Data;

import javax.persistence.*;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

/**
 * @author  sunRainAmazing
 */
@Entity
@Data
public class UserTransient {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String username;

    @Transient
    private String nickName;
    /**
     * transient 修饰的不会出现在数据库表中 
  */
    private transient String otherName;

    @Temporal(TemporalType.DATE)
    private Date birthday;

    @Column(nullable = false)
    private ZonedDateTime regTime;

    /**
     * 该属性 不会出现在 数据库表中
  */
    @Transient
    private int workingYears;
    public int getWorkingYears(){
        return ZonedDateTime.now().getYear() - regTime.getYear();
    }

    /**
     * 该属性 会出现在 数据库表中
  * @Transient 作用在方法上 不起作用,该属性依然会添加表的列中
  * 因此需要 将其放置在 该属性上,而不是方法上
  */
    private int birthdayNow;
    @Transient
    public int getBirthdayNow(){
        return ZonedDateTime.now().getYear() -
                birthday.toInstant().atZone(ZoneId.systemDefault()).getYear();
    }

    /**普通的方法*/
    public int getExperienceYears(){
        return ZonedDateTime.now().getYear() - regTime.getYear();
    }


}

/*

CREATE TABLE `user_transient` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `birthday` date DEFAULT NULL,
  `birthday_now` int(11) NOT NULL,
  `reg_time` datetime NOT NULL,
  `username` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8


 */

猜你喜欢

转载自blog.csdn.net/sunrainamazing/article/details/80783363