让Hibernate来决定是否保存或更新 : 会话 « Hibernate « Java 教程

En
Java 教程
1. 语言基础
2. 数据类型
3. 操作符
4. 流程控制
5. 类定义
6. 开发相关
7. 反射
8. 正则表达式
9. 集合
10. 线
11. 文件
12. 泛型
13. 本土化
14. Swing
15. Swing事件
16. 二维图形
17. SWT
18. SWT 二维图形
19. 网络
20. 数据库
21. Hibernate
22. JPA
23. JSP
24. JSTL
25. Servlet
26. Web服务SOA
27. EJB3
28. Spring
29. PDF
30. 电子邮件
31. 基于J2ME
32. J2EE应用
33. XML
34. 设计模式
35. 日志
36. 安全
37. Apache工具
38. 蚂蚁编译
39. JUnit单元测试
Java
Java 教程 » Hibernate » 会话 
21. 22. 3. 让Hibernate来决定是否保存或更新

File: Main.java

import java.util.HashSet;

import org.hibernate.Session;

public class Main {
  public static void main(String[] argsthrows Exception {
    HibernateUtil hibernateUtil = new HibernateUtil();
    hibernateUtil
        .executeSQLCommand("create table speakers (uid int, firstName varchar,lastName varchar, event_id int);");
    hibernateUtil
        .executeSQLCommand("create table locations (uid int, name varchar, address varchar,  event_id int);");
    hibernateUtil
        .executeSQLCommand("create table attendees (uid int, firstName varchar, lastName varchar,  event_id int);");
    hibernateUtil
        .executeSQLCommand("create table events (uid int , name varchar, start_date date, duration integer,location_id int);");

    Session session = hibernateUtil.getSession();

    Event e = new Event();
    e.setName("testSave");
    session.saveOrUpdate(e);
    session.flush();

    session.close();
    
    hibernateUtil.checkData("select * from events");
    hibernateUtil.checkData("select * from speakers");
    hibernateUtil.checkData("select * from locations");
    hibernateUtil.checkData("select * from attendees");
  }
}

File: Speaker.java

public class Speaker {

    private Long id;
    private String firstName;
    private String lastName;

    public Speaker() {
    }

    public Speaker(String firstName, String lastName) {
        setFirstName(firstName);
        setLastName(lastName);
    }

    public Long getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

File: Speaker.hbm.xml

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

<hibernate-mapping>
    <class name="Speaker" table="speakers">
        <id name="id" column="uid" type="long">
            <generator class="native"/>
        </id>
        <property name="firstName" type="string" length="20"/>
        <property name="lastName" type="string" length="20"/>
    </class>
</hibernate-mapping>

File: Attendee.hbm.xml

public class Attendee {

    private Long id;
    private String firstName;
    private String lastName;

    public Attendee() {
    }

    public Attendee(String firstName, String lastName) {
        setFirstName(firstName);
        setLastName(lastName);
    }

    public Long getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }


}

File: Attendee.hbm.xml

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

<hibernate-mapping>
    <class name="Attendee" table="attendees">
        <id name="id" column="uid" type="long">
            <generator class="native"/>
        </id>
        <property name="firstName" type="string" length="20"/>
        <property name="lastName" type="string" length="20"/>
    </class>
</hibernate-mapping>

File: Event.java

import java.util.Date;
import java.util.Set;

public class Event {

  private Long id;
  private String name;
  private Date startDate;
  private int duration;
  private Set speakers;
    private Set attendees;
    private Location location;

  public void setId(Long id) {
    this.id = id;
  }
  
  public Long getId() {
    return id;
  }

    public String getName() {
        return name;
    }

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

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public int getDuration() {
        return duration;
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }

  public void setSpeakers(Set speakers) {
    this.speakers = speakers;
  }
  
  public Set getSpeakers() {
    return speakers;
  }

    public Set getAttendees() {
        return attendees;
    }

    public void setAttendees(Set attendees) {
        this.attendees = attendees;
    }

}

File: Event.hbm.xml

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

<hibernate-mapping>
    <class name="Event" table="events">
        <id name="id" column="uid" type="long" unsaved-value="null">
            <generator class="native"/>
        </id>
        <property name="name" type="string" length="100"/>
        <property name="startDate" column="start_date"
                  type="date"/>
        <property name="duration" type="integer"/>

        <many-to-one name="location" column="location_id"
                     class="Location" cascade="all"/>
                     
                     
        <set name="speakers" cascade="all">
            <key column="event_id"/>
            <one-to-many class="Speaker"/>
        </set>
        <set name="attendees" cascade="all">
            <key column="event_id"/>
            <one-to-many class="Attendee"/>
        </set>
    </class>
</hibernate-mapping>

File: Location.java

public class Location {

    private Long id;
    private String name;
    private String address;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

File: Location.hbm.xml

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

<hibernate-mapping>
    <class name="Location" table="locations">
        <id name="id" column="uid" type="long">
            <generator class="native"/>
        </id>
        <property name="name" type="string"/>
        <property name="address" type="string"/>
    </class>
</hibernate-mapping>

File: HibernateUtil.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

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

public class HibernateUtil {
  Session session;
  Statement st;
  public HibernateUtil() throws Exception{
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    session = sessionFactory.openSession();

    // Load the JDBC driver.
    Class.forName("org.hsqldb.jdbcDriver");
    System.out.println("Driver Loaded.");
    // Establish the connection to the database.
    String url = "jdbc:hsqldb:data/tutorial";

    Connection conn = DriverManager.getConnection(url, "sa""");
    System.out.println("Got Connection.");
    st = conn.createStatement();
  }
  public Session getSession(){
    return session;
  }
  public void executeSQLCommand(String sqlthrows Exception {
    st.executeUpdate(sql);
  }

  public void checkData(String sqlthrows Exception {
    ResultSet rs = st.executeQuery(sql);
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
      System.out.print("\t"+ metadata.getColumnLabel(i + 1))
    }
    System.out.println("\n----------------------------------");

    while (rs.next()) {
      for (int i = 0; i < metadata.getColumnCount(); i++) {
        Object value = rs.getObject(i + 1);
        if (value == null) {
          System.out.print("\t       ");
        else {
          System.out.print("\t"+value.toString().trim());
        }
      }
      System.out.println("");
    }
  }
}

File: hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
        <property name="connection.url">jdbc:hsqldb:data/tutorial</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in-->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
        <!-- Enable Hibernate's current session context -->
        <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>

        <property name="hibernate.cache.use_second_level_cache">false</property>
        <property name="hibernate.cache.use_query_cache">false</property>
        
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>        
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        
        <!-- Mapping files -->
        <mapping resource="Event.hbm.xml"/>
        <mapping resource="Location.hbm.xml"/>        
        <mapping resource="Attendee.hbm.xml"/>
        <mapping resource="Speaker.hbm.xml"/>        
    </session-factory>
</hibernate-configuration>
  Download:  HibernateSaveOrUpdate.zip( 4,866 k)
21. 22. 会话
21. 22. 1. 监听会话事件
21. 22. 2. 保存和更新事件
21. 22. 3. 让Hibernate来决定是否保存或更新
21. 22. 4. 创建查询回话
21. 22. 5. Create Criteria from Session
www.java2java.com | Contact Us
Copyright 2010 - 2030 Java Source and Support. All rights reserved.
All other trademarks are property of their respective owners.