Hibernate 注解方式

第一次接触HIbernate都是以XML方式,今天来看看注解的方式如何写

1. hibernate的常用注解

//标识实体类 @Entity //该实体类对应的表 默认对应的表为类名 可通过@Table(name ="xxx")来标识实体类名与表名不同的情况 @Table //实体类的标识属性 @Id //主键的生成策略 //strategy 生产策略有以下值 //GenerationType.AUTO 由程序控制 默认值 //GenerationType.IDENTITY 由数据库生成 //GenerationType.SEQUENCE 由序列生成 需要数据库支持 @GeneratedValue //属性对应的列 可通过@Column(name="xxx")来标识属性和列名不同的情况 @Column //设置一对一关联 @OneToOne //设置一对多关联 @OneToMany //设置多对一关联 @ManyToOne //设置多对多关联 @ManyToMany //设置外键 @JoinColumn //设置关联表 @JoinTable

接下来写一个简单用户类

2. User类

package pojo; import javax.persistence.*; /** * Created by Administrator on 2018/10/29. */ @Entity @Table(name = "customer") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name="uname",length = 255,nullable = false,unique = true) private String username; @Column(name="name",length = 255) private String nickname; @Column(name="pword",length = 255,nullable = false) private String password; @Column(name = "age",nullable = false) private int age; @Column(name="address",unique = true) private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", nickname='" + nickname + '\'' + ", password='" + password + '\'' + ", age=" + age + ", address='" + address + '\'' + '}'; } }

3. hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 数据源设置 --> <property name="connection.url" >jdbc:mysql:///test</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- hibernate设置 --> <property name="hbm2ddl.auto">update</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- xml方式 属性使用resource --> <!-- 注解方式 属性使用class --> <mapping class="pojo.User"/> </session-factory> </hibernate-configuration>

4. 测试

Main.java

import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import pojo.User; /** * Created by Administrator on 2018/10/29. */ public class Main { private static final SessionFactory ourSessionFactory; static { try { Configuration configuration = new Configuration(); configuration.configure(); ourSessionFactory = configuration.buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } public static Session getSession() throws HibernateException { return ourSessionFactory.openSession(); } public static void main(final String[] args) throws Exception { final Session session = getSession(); Transaction tx = session.beginTransaction(); User user = new User(); user.setUsername("mfsvejt"); user.setNickname("魔法少女厄加特"); user.setPassword("123456"); user.setAge(18); user.setAddress("黄土高坡"); session.save(user); tx.commit(); session.createQuery("from User").list().forEach(u -> System.out.println(u)); } }

控制台输出

Hibernate: create table customer ( id integer not null auto_increment, address varchar(255), age integer not null, name varchar(255), pword varchar(255) not null, uname varchar(255) not null, primary key (id) ) engine=InnoDB Hibernate: alter table customer drop index UK_i0stw68u1778vsgy4idl3m183 Hibernate: alter table customer add constraint UK_i0stw68u1778vsgy4idl3m183 unique (address) Hibernate: alter table customer drop index UK_dyi49bfteml6qub2etkw376y9 Hibernate: alter table customer add constraint UK_dyi49bfteml6qub2etkw376y9 unique (uname) Hibernate: insert into customer (address, age, name, pword, uname) values (?, ?, ?, ?, ?) 十月 29, 2018 2:32:19 下午 org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService INFO: HHH000397: Using ASTQueryTranslatorFactory Hibernate: select user0_.id as id1_0_, user0_.address as address2_0_, user0_.age as age3_0_, user0_.name as name4_0_, user0_.pword as pword5_0_, user0_.uname as uname6_0_ from customer user0_ User{id=1, username='mfsvejt', nickname='魔法少女厄加特', password='123456', age=18, address='黄土高坡'}

可以看到我们的设置都成功了并且也输出了魔法少女,注解配置到此结束。


__EOF__

本文作者Gabriel
本文链接https://www.cnblogs.com/youarephoenix/p/15972924.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   gabriel丶  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示