hibernate注解使用

hibernate默认使用xml映射文件来关联实体和数据库表,随着系统的越来越复杂,每增加一个实体类,就需要配置一个xml映射文件,一般的系统少说也有十几个实体类,多的可能会有上百个实体,如此数量繁多的xml配置,在开发中也是很难维护的,实体一改动,配置文件就需要做相应的调整,通过xml配置的方式在实际中,也越来越不推荐使用,而是通过注解的方式。

hibernate注解,默认情况下,只需要配置@Id,@Table,@Entity等主要的属性,其余的属性和字段如果没有特别的要求,可以不用设置,如果属性createDate需要映射createdate字段,那么只需要通过如下表示:

@Column(name="createdate")
public Date createDate;

下面我们使用hibernate注解配置实现关系映射。

实体类:

BaseEntity.java

package com.xxx.hibernate4.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public class BaseEntity implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	protected Integer id;
	@Column(name="createdate")
	protected Date createDate;
	@Column(name="modifydate")
	protected Date modifyDate;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Date getCreateDate() {
		return createDate;
	}
	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
	public Date getModifyDate() {
		return modifyDate;
	}
	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}
	
}

User.java

package com.xxx.hibernate4.entity;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name="xx_user")
public class User extends BaseEntity {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String username;
	private String password;
	private String mobile;
	private int age;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + 
                ", mobile=" + mobile + ", age=" + age + ", id="
				+ id + "]";
	}
	
	
}

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
  <session-factory>
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="connection.url">jdbc:mysql:///hibernate4?useUnicode=true&amp;characterEncoding=UTF-8</property>
      <property name="connection.username">hadoop</property>
      <property name="connection.password">hadoop</property>
      <property name="connection.pool_size">1</property>
      <property name="dialect">org.hibernate.dialect.MySQL57InnoDBDialect</property>
      <property name="show_sql">true</property>
      <property name="format_sql">true</property>
      <property name="hbm2ddl.auto">update</property>
      <mapping class="com.xxx.hibernate4.entity.User"/>
  </session-factory>
</hibernate-configuration>

hibernate.cfg.xml配置文件中mapping以前是引入的user.hbm.xml配置文件,现在改为了class="com.xxx.hibernate4.entity.User" 直接指向了实体类。

App.java

package com.xxx.hibernate4;
import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.xxx.hibernate4.entity.BaseEntity;
import com.xxx.hibernate4.entity.User;

@SuppressWarnings("deprecation")
public class App {
	public static SessionFactory sessionFactory;
	public static final ThreadLocal<Session> session = new ThreadLocal<>();
	static {
		try {
			Configuration cfg = new Configuration().configure();
			sessionFactory = cfg.buildSessionFactory();
		} catch (HibernateException e) {
			e.printStackTrace();
			System.err.println("Initialize SessionFactory fail "+e);
		}
	}
	
	public static Session getSession() {
		Session sess = (Session)session.get();
		if(sess==null) {
			sess = sessionFactory.openSession();
			session.set(sess);
		}
		return sess;
	}
	
	public static void closeSession() {
		Session sess = (Session)session.get();
		if(sess!=null) {
			sess.close();
		}
		session.set(null);
		sessionFactory.close();
	}
	
	public static void add(BaseEntity entity) {
		Session sess = getSession();
		Transaction tx = sess.beginTransaction();
		entity.setCreateDate(new Date());
		entity.setModifyDate(new Date());
		sess.save(entity);
		tx.commit();
		closeSession();
	}
	
	public static void search(String className) {
		Session sess = getSession();
		Integer id = 1;
		Object object = sess.get(className, id);
		System.out.println(object);
		closeSession();
	}
	
    public static void main( String[] args ){
    	
    	User user = new User();
    	user.setUsername("hadoop");
    	user.setPassword("hadoop");
    	user.setAge(20);
    	user.setMobile("15011186303");
    	add(user);
    	
    	//search("com.xxx.hibernate4.entity.User");
    }
}

 运行打印信息:

三月 18, 2019 5:37:23 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
三月 18, 2019 5:37:23 下午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.10.Final}
三月 18, 2019 5:37:23 下午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
三月 18, 2019 5:37:23 下午 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
三月 18, 2019 5:37:23 下午 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
三月 18, 2019 5:37:23 下午 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
三月 18, 2019 5:37:23 下午 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
三月 18, 2019 5:37:23 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
三月 18, 2019 5:37:23 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql:///hibernate4?useUnicode=true&useSSL=false&characterEncoding=UTF-8]
三月 18, 2019 5:37:23 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=hadoop, password=****}
三月 18, 2019 5:37:23 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
三月 18, 2019 5:37:23 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
三月 18, 2019 5:37:24 下午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL57InnoDBDialect
三月 18, 2019 5:37:24 下午 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
三月 18, 2019 5:37:24 下午 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
三月 18, 2019 5:37:24 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
三月 18, 2019 5:37:24 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
三月 18, 2019 5:37:24 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
三月 18, 2019 5:37:24 下午 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: hibernate4.xx_user
三月 18, 2019 5:37:24 下午 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [password, modifydate, mobile, createdate, id, age, username]
三月 18, 2019 5:37:24 下午 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
三月 18, 2019 5:37:24 下午 org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [primary]
三月 18, 2019 5:37:24 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: 
    insert 
    into
        xx_user
        (createdate, modifydate, age, mobile, password, username) 
    values
        (?, ?, ?, ?, ?, ?)
三月 18, 2019 5:37:24 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql:///hibernate4?useUnicode=true&useSSL=false&characterEncoding=UTF-8]

通过注解,我们省去了很多xml配置,大大减轻了工作量,如果修改了实体类,增加或者修改属性,无需担心实体和表的映射问题。

另外@Column属性,可以修改varchar长度的,比如mobile一般默认是11位的,这里我们通过@Column(length=11)来设置mobile的长度,节省存储空间。

@Column(length=11)
private String mobile;

设置前生成的表结构:

限制长度11之后表结构:

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luffy5459

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值