Hibernate Annotation入门

废话不多说,直接上例子(附件)


数据库脚本:


-- MySQL dump 10.13  Distrib 5.1.55, for Win32 (ia32)
--
-- Host: localhost    Database: hibernate_demo
-- ------------------------------------------------------
-- Server version	5.1.55-community

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `user`
--

DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `age` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `user`
--

LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (1,'zhaoyp',24),(2,'zyp',24),(3,'zyp',24);
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2012-08-15 19:33:54
 




程序代码:


//User.java


package com.zyp.examples;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import javax.persistence.Entity;

import org.hibernate.annotations.GenericGenerator;

/**
 * User entity. @author MyEclipse Persistence Tools
 */

@Entity
@Table(name="user")
public class User implements java.io.Serializable {

	// Fields

	private static final long serialVersionUID = 3696937800867434239L;

	@Id
	@GeneratedValue(generator="paymentableGenerator", strategy=GenerationType.IDENTITY)
	@GenericGenerator(name="paymentableGenerator", strategy="increment")
	@Column(name="id")
	private Integer id;
	
	@Column(name="name", insertable=true, nullable=false, updatable=true)
	private String name;
	
	@Column(name="age", insertable=true, nullable=false, updatable=true)
	private Integer age;

	// Constructors

	/** default constructor */
	public User() {
	}

	/** full constructor */
	public User(String name, Integer age) {
		this.name = name;
		this.age = age;
	}

	// Property accessors

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return this.age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

}
 



//hibernate.cfg.xml

	<property name="show_sql">true</property>
	<property name="format_sql">true</property>
	<property name="myeclipse.connection.profile">mysql</property>
	
	<!-- 请注意,需要映射到类文件 -->
	<mapping class="com.zyp.examples.User" />
 


//HibernateUtil.java

package com.zyp.examples;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static SessionFactory sessionFactory;
	static {
		try {
//			sessionFactory = new Configuration().configure()
//					.buildSessionFactory();
			//使用注解之后不能使Configuration()类
			sessionFactory = new AnnotationConfiguration()
				.configure().buildSessionFactory();
		} catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void shutdown() {
		getSessionFactory().close();
	}
}
 


//AnnotationTest.java

package com.zyp.examples;

import org.hibernate.Session;

public class AnnotationTest {

	public static void main(String[] args) {
		addUser();
	}
	
	public static void addUser()
	{
		User user = new User();
		user.setAge(24);
		user.setName("zyp");
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		session.save(user);
		session.getTransaction().commit();
	}

}
 

在编写这个例子的过程中可能遇到的问题:


(1)没有将实体类文件class映射到Hibernate.cfg.xml文件中,需要在hibernate.cfg.xml中添加类映射;


Caused by: org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.zyp.examples.User"/>


(2)在使用annotation的时候使用了hibernate中的类而不是javax.persistent.*中的类而导致错误,看清楚用到的是哪个包下的哪个类


(3)主键生成方式写错导致如下的错误:


Caused by: org.hibernate.MappingException: could not interpret id generator strategy: GenerationType.AUTO
    at org.hibernate.id.IdentifierGeneratorFactory.getIdentifierGeneratorClass(IdentifierGeneratorFactory.java:151)

	@Id
	@GeneratedValue(generator="paymentableGenerator", strategy=GenerationType.IDENTITY)
	@GenericGenerator(name="paymentableGenerator", strategy="hibernate中主键的生成策略名")
        //用的increment就写increment
	@Column(name="id")
	private Integer id;

猜你喜欢

转载自paladin1988.iteye.com/blog/1633258
今日推荐