`

Hibernate one -to -one mapping for Oracle auto-increment key

 
阅读更多

  1. DB table create

 

  The parent table

 

create table stock (
    stock_id number(10)  not null,
    stock_code varchar2(10) not null,
    stock_name varchar2(10) not null,
    primary key (stock_id)
);

  the child table

 

 

create table stock_detail(
    stock_id number(10) not null,
    comp_name varchar2(100) not null,
    comp_desc varchar2(100) not null,
    remark_desc varchar2(100) not null,
    listed_date date not null,
    primary key (stock_id),
    foreign key(stock_id) references stock(stock_id)
    )

 below is create the sequence for the parent table for the primary key

 

 

create sequence stock_seq start with 1 increment by 1 nomaxvalue;

 below trigger auto-update the primary key for the parent table

 

 

create or replace trigger stock_trigger
before insert on stock
for each row
    begin
        select stock_seq.nextval into:new.stock_id from dual;
    end;
/   

 below is test for above code, don't need in the demo, u can ignore

 

 

insert into stock(stock_code,stock_name) values('112','112_com')
insert into stock_detail(stock_id,comp_name,comp_desc,remark_desc,listed_date) 
values(4,'111','111','111',to_date('2013-04-05','yyyy-mm-dd'))
desc stock;
desc stock_detail;
select * from stock;    
select * from stock_detail;  

create or replace procedure proc_dropifexist(
    p_table in varchar2
 ) is
   v_count number(10);
   begin
    select count(*)
    into v_count
    from user_tables
    where table_name = upper(p_table);
    if v_count > 0 then
     execute immediate 'drop table ' || p_table ||' purge';
    end if;
  end proc_dropifexist;          
    
exec proc_dropifexist('stock');

 

 

2. pojo & sessionFactory

 

1. Stock:

 

public class Stock implements java.io.Serializable {
    private int stockId;
    private String stockCode;
    private String stockName;
    private StockDetail stockDetail;
    
  ... 
//ignore the constructor & getter/setter
}

 2. StockDetail:

 

 

public class StockDetail implements java.io.Serializable {
    private int stockId;
    private Stock stock;
    private String compName;
    private String compDesc;
    private String remarkDesc;
    private Date listedDate;
...
//ingore the constructor & getter/setter
}

 

3. SesstionFactory get via HibernateUtil

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

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();
    
    private static SessionFactory buildSessionFactory() {
        try {
            //create SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch(Throwable ex) {
            System.err.println("Initial SessionFactory creation failed: " + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public static void shutdown() {
        getSessionFactory().close();
    }
}

 

4. xml config file:

 

 Stock.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="net.codercn.module.Stock" table="stock">
		<id name="stockId" type="int">
			<column name="stock_id"/>
			<generator class="sequence">
				<param name="sequence">stock_seq</param>
			</generator>
		</id>
		<property name="stockCode" type="string">
			<column name="stock_code" length="10" not-null="true"/>
		</property>
		<property name="stockName" type="string">
			<column name="stock_name" length="10" not-null="true"/>
		</property>
		<one-to-one name="stockDetail" class="net.codercn.module.StockDetail" cascade="save-update"></one-to-one>
	</class>
</hibernate-mapping>

 

StockDetail.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="net.codercn.module.StockDetail" table="stock_detail">
		<id name="stockId" type="int">
			<column name="stock_id"/>
			<generator class="foreign">
				<param name="property">stock</param>
			</generator>
		</id>
		<one-to-one name="stock" class="net.codercn.module.Stock" constrained="true"></one-to-one>
		<property name="compName" type="string">
			<column name="comp_name" length="100" not-null="true"/>
		</property>
		<property name="compDesc" type="string">
			<column name="comp_desc" length="100" not-null="true"/>
		</property>
		<property name="remarkDesc" type="string">
			<column name="remark_desc" length="100" not-null="true"/>
		</property>
		<property name="listedDate" type="date">
			<column name="listed_date" length="10" not-null="true"/>
		</property>
	</class>
</hibernate-mapping>

 

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.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<property name="hibernate.connection.url">jdbc:oracle:thin:@~~~</property>
		<property name="hibernate.connection.username">~~~</property>
		<property name="hibernate.connection.password">~~</property>
		<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
		<property name="hibernate.default_schema">~~~</property>
		<mapping resource="hibernate/Stock.hbm.xml" />
		<mapping resource="hibernate/StockDetail.hbm.xml" />
		
	</session-factory>
</hibernate-configuration>

 

 

5. test

package net.codercn;

import java.util.Date;

import net.codercn.module.Stock;
import net.codercn.module.StockDetail;
import net.codercn.util.HibernateUtil;

import org.hibernate.Session;

public class App {
    public static void main(String[] args) {
        System.out.println("Maven + Hibernate + Oracle");
        Session session = HibernateUtil.getSessionFactory().openSession();
        
        session.beginTransaction();
        
        Stock stock = new Stock();
        stock.setStockCode("111");
        stock.setStockName("God");
        
        StockDetail stockDetail = new StockDetail();
        stockDetail.setCompName("God Internal");
        stockDetail.setCompDesc("Greatest Company in heaven");
        stockDetail.setRemarkDesc("Nothing Special");
        stockDetail.setListedDate(new Date());
        
        stock.setStockDetail(stockDetail);
        stockDetail.setStock(stock);
        
        session.save(stock);
        session.getTransaction().commit();
        System.out.println("insert a record into table");
        
    }
}

 

6. maven 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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>net.codercn</groupId>
  <artifactId>Hibernate</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Hibernate</name>
  <url>http://maven.apache.org</url>
  
  <repositories>
  	<repository>
  		<id>JBoss repository</id>
  		<url>http://repository.jboss.org/nexus/content/groups/public/</url>
  	</repository>
  </repositories>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <!--  Hibernate  -->
    <dependency>
    	<groupId>org.hibernate</groupId>
    	<artifactId>hibernate-core</artifactId>
    	<version>3.6.3.Final</version>
    </dependency>
    <dependency>
    	<groupId>javassist</groupId>
    	<artifactId>javassist</artifactId>
    	<version>3.12.1.GA</version>
    </dependency>
    <!--  oracle jdbc driver -->
    <dependency>
    	<groupId>com.oracle</groupId>
    	<artifactId>oraclejdbc</artifactId>
    	<version>10.2.0.3.0</version>
    </dependency>
  </dependencies>
</project>

 

 7. manually install  JDBC driver to local repository:

  • get jdbc driver and put it in an folder(if installed oracle, it always locate at : D:\oracle\product\10.1.0\db_1\jdbc\lib\ojdbc14.jar)
  • go to above jdbc driver folder, run below maven command:
 mvn install:install-file -Dfile=ojdbc14.jar -DgroupId=com.oracle -DartifactId
=oraclejdbc -Dversion=10.1.0.2.0 -Dpackaging=jar -DgeneratePom=true
 check your maven local repository (~maven\repository\com\oracle\oracle\10.1.0.2.0), it will install the jdbc driver
 
 Above is for XML style, annotation style as below:
package net.codercn.module;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "stock",  uniqueConstraints ={
        @UniqueConstraint(columnNames = "stock_name"),
        @UniqueConstraint(columnNames = "stock_code")
})
public class Stock implements java.io.Serializable {
    private int stockId;
    private String stockCode;
    private String stockName;
    private StockDetail stockDetail;
    
    public Stock(){}

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "my_entity_seq_generator")
    @SequenceGenerator(name = "my_entity_seq_generator", sequenceName = "stock_seq")
    @Column(name = "stock_id", unique = true, nullable = false)
    public int getStockId() {
        return stockId;
    }

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

    @Column(name = "stock_code", unique = true, nullable = false, length = 10)
    public String getStockCode() {
        return stockCode;
    }

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

    @Column(name = "stock_name", unique = true, nullable = false, length = 10)
    public String getStockName() {
        return stockName;
    }

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

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "stock", cascade = CascadeType.ALL)
    public StockDetail getStockDetail() {
        return stockDetail;
    }

    public void setStockDetail(StockDetail stockDetail) {
        this.stockDetail = stockDetail;
    }
    
}
 

 

package net.codercn.module;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = "stock_detail")
public class StockDetail implements java.io.Serializable {
    private int stockId;
    private Stock stock;
    private String compName;
    private String compDesc;
    private String remarkDesc;
    private Date listedDate;
    
    public StockDetail(){}

    @GenericGenerator(name = "generator", strategy = "foreign",
            parameters = @Parameter(name = "property", value = "stock"))
    @Id
    @GeneratedValue(generator = "generator")
    @Column(name = "stock_id", unique = true, nullable = false)
    public int getStockId() {
        return stockId;
    }

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

    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    public Stock getStock() {
        return stock;
    }

    public void setStock(Stock stock) {
        this.stock = stock;
    }

    @Column(name = "comp_name", nullable = false, length = 100)
    public String getCompName() {
        return compName;
    }

    public void setCompName(String compName) {
        this.compName = compName;
    }

    @Column(name = "comp_desc", nullable = false)
    public String getCompDesc() {
        return compDesc;
    }

    public void setCompDesc(String compDesc) {
        this.compDesc = compDesc;
    }
    @Column(name = "remark_desc", nullable = false)
    public String getRemarkDesc() {
        return remarkDesc;
    }

    public void setRemarkDesc(String remarkDesc) {
        this.remarkDesc = remarkDesc;
    }

    @Temporal(TemporalType.DATE)
    @Column(name = "listed_date", nullable = false, length = 10)
    public Date getListedDate() {
        return listedDate;
    }

    public void setListedDate(Date listedDate) {
        this.listedDate = listedDate;
    }

  
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics