美文网首页工作中源代码学习
hibernate-jpa-api.jar中的@Transien

hibernate-jpa-api.jar中的@Transien

作者: ___TheOne___ | 来源:发表于2018-05-25 17:02 被阅读9次

    1.标签描述:

    package javax.persistence;
    
    import java.lang.annotation.Retention;
    import java.lang.annotation.Target;
    
    import static java.lang.annotation.ElementType.FIELD;
    import static java.lang.annotation.ElementType.METHOD;
    import static java.lang.annotation.RetentionPolicy.RUNTIME;
    
    /**
     * Specifies that the property or field is not persistent. It is used
     * to annotate a property or field of an entity class, mapped
     * superclass, or embeddable class.
     *
     * <pre>
     *    Example:
     *
     *    &#064;Entity
     *    public class Employee {
     *        &#064;Id int id;
     *        &#064;Transient User currentUser;
     *        ...
     *    }
     * </pre>
     *
     * @since Java Persistence 1.0
     */
    @Target({ METHOD, FIELD })
    @Retention(RUNTIME)
    public @interface Transient {
    }
    

    核心点:这个标签是用来指定属性或字段,是瞬时状态,不持久化到数据库中。

    2.标签放置位置:亲测只有放置到属性的GET方法上,才会起作用!

    @Entity
    public class Books {
        private Integer id;
        private String name;
        private String author;
        private Integer price;
        private String description;
        private Date createTime;
        private Date updateTime;
    
        private String newParameter;
    
    
        @Transient
        public String getNewParameter() {
            return newParameter;
        }
    
        public void setNewParameter(String newParameter) {
            this.newParameter = newParameter;
        }
    ...
    

    控制台Hibernate底层执行的SQL语句:可以看到在String newParameter;对应的GET方法上加上@Transient标签,插入SQL语句将自动排除这个字段。

    Hibernate: 
        insert 
        into
            books
            (author, create_time, description, name, price, update_time) 
        values
            (?, ?, ?, ?, ?, ?)
    {"description":"好好学习,承担医学传承","id":21,"name":"神农本草经"}
    

    相关文章

      网友评论

        本文标题:hibernate-jpa-api.jar中的@Transien

        本文链接:https://www.haomeiwen.com/subject/aksujftx.html