hibernate用注解替代映射文件

来源:互联网 发布:源码论坛 编辑:程序博客网 时间:2024/06/17 15:24
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>
0 0