hibernate用注解替代映射文件


1.首先把原來的映射文件刪掉,給實體類添加注解:

@Entity        //聲明當前類為hibernate映射到數據庫中的實體類
@Table(name="news")        //聲明table的名稱
public class News {
    @Id        //聲明此列為主鍵,作為映射對象的標識符
    /**
     *  @GeneratedValue注解來定義生成策略
     *  GenerationType.TABLES 當前主鍵的值單獨保存到一個數據庫的表中
     *  GenerationType.SEQUENCE  利用底層數據庫提供的序列生成標識符
     *  GenerationType.IDENTITY 采取數據庫的自增策略
     *  GenerationType.AUTO 根據不同數據庫自動選擇合適的id生成方案,這里使用mysql,為遞增型
     */
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    
    @Column(name="title",nullable=false)
    private String title;
    
    @Column(name="content",nullable=false)
    private String content;
    
    @Column(name="begintime",nullable=false)
    private Date begintime;
    
    @Column(name="username",nullable=false)
    private String username;

    public News() {
        super();
    }
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    
    public Date getBegintime() {
        return begintime;
    }
    public void setBegintime(Date begintime) {
        this.begintime = begintime;
    }
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    
    
}

想知道hibernate注解怎么使用的,可以參考我上一篇的博客

http://www.cnblogs.com/qq1272850043/p/5960365.html

 

2.添加完注解之后,到applicationContext.xml文件中把查找對應映射文件的property刪了

<!-- 把這個刪了 -->
<property name="mappingResources">
    <list>
        <value>news/entity/News.hbm.xml</value>
    </list>
</property>

 

3.然后在applicationContext.xml中加上這個

<!-- 掃描實體類包,解析實體類的注解 -->
<property name="packagesToScan">
    <list>
        <!-- 這里value值添實體類所在的包 -->
        <value>news.entity</value>
    </list>
</property>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM