這一次先介紹相關的設定,有hibernate.cfg.xml , HibernateUtil.java
還有一個資料庫的java 物件 UserData.java
1.先產生一個Hibernate的設定檔,NetBeans有精靈可以幫助你
一般我都會再加兩個參數,讓Debug更容易些
hibernate.show_sql = true
hibernate.current_session_context_class = thread
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/demo</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.connection.password">qwerfdsa</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
2.產生一個HibernateUtil 主要是去讀取config裡的參數產生Connection讓其他的程式使用
一樣NetBeans也有精靈可以快速產生,如下
package demo;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
3.接下第三步就是產生一個和資料庫一樣的java物件
注意變數的第一個字母要小寫
package demo;
public class UserData {
private String userid;
private String userpassword;
private String username;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpassword() {
return userpassword;
}
public void setUserpassword(String userpassword) {
this.userpassword = userpassword;
}
}