欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hiberante+Mysql+Maven2 XML配置原型

程序员文章站 2022-03-29 23:23:48
...
使用Maven3+Hibernate 3.1+Mysql实现一个简单的模型

使用到的工具:
   Eclipse 4.3
   Maven 3.1
   Hibernate 3.1rc2
   MySQL 5.0


具体搭建实现步骤:
  1.创建一个数据库为David。
  2.在David数据库中创建一个表
DROP TABLE IF EXISTS `stock`;
CREATE TABLE `stock` (
  `STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `STOCK_CODE` VARCHAR(10) NOT NULL,
  `STOCK_NAME` VARCHAR(20) NOT NULL,
  PRIMARY KEY (`STOCK_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
  UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  3.在Eclipse中创建一个Maven Project
  4.编写POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.david.common</groupId>
  <artifactId>SpringExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SpringExample</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
<dependency>
    <groupId>hibernate</groupId>
    <artifactId>hibernate</artifactId>
    <version>3.1rc2</version>
</dependency>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.9</version>
	</dependency>
	
	<!-- Hibernate library dependecy start -->
	<dependency>
		<groupId>dom4j</groupId>
		<artifactId>dom4j</artifactId>
		<version>1.6.1</version>
	</dependency>
 
	<dependency>
		<groupId>commons-logging</groupId>
		<artifactId>commons-logging</artifactId>
		<version>1.1.1</version>
	</dependency>
 
	<dependency>
		<groupId>commons-collections</groupId>
		<artifactId>commons-collections</artifactId>
		<version>3.2.1</version>
	</dependency>
 
	<dependency>
		<groupId>cglib</groupId>
		<artifactId>cglib</artifactId>
		<version>2.2</version>
	</dependency>
	<!-- Hibernate library dependecy end -->
 
	<dependency>
		<groupId>javax.transaction</groupId>
		<artifactId>jta</artifactId>
		<version>1.1</version>
	</dependency>
	<dependency>
    <groupId>com.jolira</groupId>
    <artifactId>asm</artifactId>
    <version>3.3.0</version>
</dependency>
  </dependencies>
</project>

5.配置Stock.hbm.xml 这个文件要放在src/main/resources/com/david/common/Stock.hbm.xml
 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping>
    <class name="com.david.common.Stock" table="stock" catalog="david">
        <id name="stockId" type="java.lang.Integer">
            <column name="STOCK_ID" />
            <generator class="identity" />
        </id>
        <property name="stockCode" type="string">
            <column name="STOCK_CODE" length="10" not-null="true" unique="true" />
        </property>
        <property name="stockName" type="string">
            <column name="STOCK_NAME" length="20" not-null="true" unique="true" />
        </property>
    </class>
</hibernate-mapping>

6.编写Stock实体类
public class Stock implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	private Integer stockId;
	private String stockCode;
	private String stockName;
	
	public Stock () {
		
	}
	
	public Stock(String stockCode, String  stockName){
		this.stockCode = stockCode;
		this.stockName = stockName;
	}

	public Integer getStockId() {
		return stockId;
	}

	public void setStockId(Integer stockId) {
		this.stockId = stockId;
	}

	public String getStockCode() {
		return stockCode;
	}

	public void setStockCode(String stockCode) {
		this.stockCode = stockCode;
	}

	public String getStockName() {
		return stockName;
	}

	public void setStockName(String stockName) {
		this.stockName = stockName;
	}

	public String toString(){
		return "[ stockId:"+stockId
				+" stockName:"+stockName+" stockCode:"+stockCode+"]";
	}
}


7.编写一个简单的Hibernate工具类。用来获取Session等操作
public class HibernateUtil {
	
	private static final SessionFactory sessionFactory = buildSessionFactory();
	
    public static SessionFactory buildSessionFactory(){
    	try {
			 return new Configuration().configure().buildSessionFactory();
		} catch (Exception ex) {
			
			System.err.println("Initial SessionFactory creation fails"+ex);
			throw new ExceptionInInitializerError(ex);
	   }
    }
    
    public static SessionFactory getSessionFactory(){
    	return sessionFactory;
    }
    
    public static void shutdown(){
    	getSessionFactory().close();
    }
}

8.最后编写Hibernate.cfg.xml放在/src/main/resources/hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/david</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        
        <mapping resource="com/david/common/Stock.hbm.xml"></mapping>
        
    </session-factory>
</hibernate-configuration>

9.写个测试类来验证下配置是否有问题
public class App 
{
    public static void main( String[] args )
    {
       System.out.println("Maven +hibernate + Mysql");
       
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Stock stock = new Stock();
        
        stock.setStockCode("47135");
        stock.setStockName("GENM");
        session.save(stock);
        session.getTransaction().commit();
        
    }
}


10.运行发现报错了。报错信息如下:
Exception in thread "main" java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V
	at net.sf.cglib.core.DebuggingClassWriter.<init>(DebuggingClassWriter.java:47)
	at net.sf.cglib.core.DefaultGeneratorStrategy.getClassWriter(DefaultGeneratorStrategy.java:30)
	at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:24)
	at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
	at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:144)
	at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:116)
	at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
	at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)
	at org.hibernate.impl.SessionFactoryImpl.<clinit>(SessionFactoryImpl.java:362)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1145)
	at com.david.utils.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
	at com.david.utils.HibernateUtil.<clinit>(HibernateUtil.java:12)
	at com.david.common.App.main(App.java:17)


11.解决这个问题:原来是包的冲突(asm没有引入3.3版本的话,由于maven的依赖传递会自动引入一个1.5.3版本的asmjar包,这个包会跟cglib 2.2版本的包发生冲突。因此要显示的引入一个高版本的asm包)

在pom.xml中显示加入
	<dependency>
    <groupId>com.jolira</groupId>
    <artifactId>asm</artifactId>
    <version>3.3.0</version>
</dependency>

12.再次运行就没问题了。