第一次接觸HIbernate都是以XML方式,今天來(lái)看看注解的方式如何寫
1. hibernate的常用注解
//標(biāo)識(shí)實(shí)體類
@Entity
//該實(shí)體類對(duì)應(yīng)的表 默認(rèn)對(duì)應(yīng)的表為類名 可通過(guò)@Table(name ="xxx")來(lái)標(biāo)識(shí)實(shí)體類名與表名不同的情況
@Table
//實(shí)體類的標(biāo)識(shí)屬性
@Id
//主鍵的生成策略
//strategy 生產(chǎn)策略有以下值
//GenerationType.AUTO 由程序控制 默認(rèn)值
//GenerationType.IDENTITY 由數(shù)據(jù)庫(kù)生成
//GenerationType.SEQUENCE 由序列生成 需要數(shù)據(jù)庫(kù)支持
@GeneratedValue
//屬性對(duì)應(yīng)的列 可通過(guò)@Column(name="xxx")來(lái)標(biāo)識(shí)屬性和列名不同的情況
@Column
//設(shè)置一對(duì)一關(guān)聯(lián)
@OneToOne
//設(shè)置一對(duì)多關(guān)聯(lián)
@OneToMany
//設(shè)置多對(duì)一關(guān)聯(lián)
@ManyToOne
//設(shè)置多對(duì)多關(guān)聯(lián)
@ManyToMany
//設(shè)置外鍵
@JoinColumn
//設(shè)置關(guān)聯(lián)表
@JoinTable
接下來(lái)寫一個(gè)簡(jiǎn)單用戶類
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>
<!-- 數(shù)據(jù)源設(shè)置 -->
<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設(shè)置 -->
<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. 測(cè)試
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));
}
}
控制臺(tái)輸出
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='黃土高坡'}
可以看到我們的設(shè)置都成功了并且也輸出了魔法少女,注解配置到此結(jié)束。