在日常java C/S系统开发,我接触的很少使用Hibernate做为MVC中数据库映射开发,所以我没事的时候做了一个C/S结合Hibernate数据库映射开发的实例,下面我将Hibernate在Eclipse中的配置详细写出来,很多网上接触到的文章都是错的,只是增加上了Hibernate.jar,其他都没有介绍。
开始配置:
A:下载Hibernate3.jar必备包。
B:下载HibernateSynchronizer-3.1.9.zip,Hibernate与数据库的映射插件。
C:下载Hibernate3其他附属包,不然在后面开发的时候会不断出现缺包的异常。
D:上面所有的包可以到这个地址下载:http://download.csdn.net/detail/captaingan/3716351
E:解压上面下载的包,将其中的HibernateSynchronizer-3.1.9.zip包解压,将底层的文件夹 com.hudson.hibernatesynchronizer_3.1.9拷贝到Eclipse安装目录的Plugin目录中。
F:重启Eclipse,
G:新建一个C/S项目,我的工程是使用的SWT作为我的前台开发的。添加前面的JAR文件到工程中。
src目录下log4j.properties是必须的:
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=warn, stdout
log4j.logger.org.hibernate=error
H:选中项目File-NEW-OTHERS-HIBERNATE(如果前面插件安装成功后,会出现)-Hibernate Configuration File
Next
填上数据库相关信息
-> Finish 就会出现下图的hibenrate配置XML
再然后
File - New - Other - Hibernate - Hibernate Mapping File - Next 出现下图:
Table Pattern 和 Schema Pattern不要填写,然后 Refresh,在Table中会出现数据库中的表格,选中需要映射的表格,然后Finish,出现下图情况:
选中上面的SbdWorkerTab.hbm.xml 右键 选中 Hibernate Synchronizer -> Synchronizer File出现上图出现的需要 BaseSbdWorkerTab.java和SbdWorkerTab.java两个文件
再次上Hibernate Synchronizer ->Add Mapping Refference添加映射配置到hibernate.cfg.xml文件中。
然后添加自己的DAO访问方法我的方法如下:
package com.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import com.ORM.SbdWorkerTab;
public class RegisterDao implements WorkerDaoInterface {
public void addWorker(SbdWorkerTab sbdWorkerTab) {
Configuration config = new Configuration().configure();
SessionFactory sFactory = config.buildSessionFactory();
Session session = sFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(sbdWorkerTab);
transaction.commit();
session.close();
}
public List<SbdWorkerTab> listWorker() {
List<SbdWorkerTab> sworkerList = new ArrayList<SbdWorkerTab>();
String HQL = "Select s From SbdWorkerTab as s";
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Query query = session.createQuery(HQL);
Transaction trans = session.beginTransaction();
sworkerList = query.list();
trans.commit();
return sworkerList;
}
@Override
public void deleteWorker(String workerId) {
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction trans = session.beginTransaction();
SbdWorkerTab sbdWorkerTab = (SbdWorkerTab) session.load(
SbdWorkerTab.class, workerId);
session.delete(sbdWorkerTab);
trans.commit();
}
@Override
public void updateWorker(SbdWorkerTab sbdWorkerTab) {
Configuration config = (new Configuration()).configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.update(sbdWorkerTab);
transaction.commit();
}
}
package com.dao;
import java.util.List;
import com.ORM.SbdWorkerTab;
public interface WorkerDaoInterface {
public void addWorker(SbdWorkerTab sbdWorkerTab);
public List<SbdWorkerTab> listWorker();
public void deleteWorker(String workerId);
public void updateWorker(SbdWorkerTab sbdWorkerTab);
}
在前台访问前面的DAO方法就可以了。
这里是分割线
========================2015年分割线===========================
下面是所有代码
RegisterDao
package com.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import com.ORM.SbdWorkerTab;
public class RegisterDao implements WorkerDaoInterface {
public void addWorker(SbdWorkerTab sbdWorkerTab) {
Configuration config = new Configuration().configure();
SessionFactory sFactory = config.buildSessionFactory();
Session session = sFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(sbdWorkerTab);
transaction.commit();
session.close();
}
public List<SbdWorkerTab> listWorker() {
List<SbdWorkerTab> sworkerList = new ArrayList<SbdWorkerTab>();
String HQL = "Select s From SbdWorkerTab as s";
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Query query = session.createQuery(HQL);
Transaction trans = session.beginTransaction();
sworkerList = query.list();
trans.commit();
return sworkerList;
}
@Override
public void deleteWorker(String workerId) {
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction trans = session.beginTransaction();
SbdWorkerTab sbdWorkerTab = (SbdWorkerTab) session.load(
SbdWorkerTab.class, workerId);
session.delete(sbdWorkerTab);
trans.commit();
}
@Override
public void updateWorker(SbdWorkerTab sbdWorkerTab) {
Configuration config = (new Configuration()).configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.update(sbdWorkerTab);
transaction.commit();
}
}
WorkerDaoInterface
package com.dao;
import java.util.List;
import com.ORM.SbdWorkerTab;
public interface WorkerDaoInterface {
public void addWorker(SbdWorkerTab sbdWorkerTab);
public List<SbdWorkerTab> listWorker();
public void deleteWorker(String workerId);
public void updateWorker(SbdWorkerTab sbdWorkerTab);
}
SbdWorkerTab
package com.ORM;
import com.ORM.base.BaseSbdWorkerTab;
public class SbdWorkerTab extends BaseSbdWorkerTab {
private static final long serialVersionUID = 1L;
public SbdWorkerTab () {
super();
}
public SbdWorkerTab (
java.lang.String workerId,
java.lang.String workerName,
java.lang.String workerPassword,
java.lang.String workerRole) {
super (
workerId,
workerName,
workerPassword,
workerRole);
}
}
SbdWorkerTab.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.ORM">
<class name="SbdWorkerTab" table="sbd_worker_tab">
<meta attribute="sync-DAO">false</meta>
<id name="Id" type="string" column="worker_id" />
<property name="WorkerName" column="worker_name" type="string"
not-null="true" length="15" />
<property name="WorkerPassword" column="worker_password"
type="string" not-null="true" length="12" />
<property name="WorkerRole" column="worker_role" type="string"
not-null="true" length="15" />
</class>
</hibernate-mapping>
BaseSbdWorkerTab
package com.ORM.base;
import java.io.Serializable;
/**
* This is an object that contains data related to the sbd_worker_tab table.
* Do not modify this class because it will be overwritten if the configuration file
* related to this class is modified.
*
* @hibernate.class
* table="sbd_worker_tab"
*/
public abstract class BaseSbdWorkerTab implements Serializable {
public static String REF = "SbdWorkerTab";
public static String PROP_WORKER_ROLE = "WorkerRole";
public static String PROP_WORKER_NAME = "WorkerName";
public static String PROP_ID = "Id";
public static String PROP_WORKER_PASSWORD = "WorkerPassword";
public BaseSbdWorkerTab () {
initialize();
}
public BaseSbdWorkerTab (java.lang.String id) {
this.setId(id);
initialize();
}
public BaseSbdWorkerTab (
java.lang.String id,
java.lang.String workerName,
java.lang.String workerPassword,
java.lang.String workerRole) {
this.setId(id);
this.setWorkerName(workerName);
this.setWorkerPassword(workerPassword);
this.setWorkerRole(workerRole);
initialize();
}
protected void initialize () {}
private int hashCode = Integer.MIN_VALUE;
private java.lang.String id;
private java.lang.String workerName;
private java.lang.String workerPassword;
private java.lang.String workerRole;
public java.lang.String getId () {
return id;
}
public void setId (java.lang.String id) {
this.id = id;
this.hashCode = Integer.MIN_VALUE;
}
public java.lang.String getWorkerName () {
return workerName;
}
public void setWorkerName (java.lang.String workerName) {
this.workerName = workerName;
}
public java.lang.String getWorkerPassword () {
return workerPassword;
}
public void setWorkerPassword (java.lang.String workerPassword) {
this.workerPassword = workerPassword;
}
public java.lang.String getWorkerRole () {
return workerRole;
}
public void setWorkerRole (java.lang.String workerRole) {
this.workerRole = workerRole;
}
public boolean equals (Object obj) {
if (null == obj) return false;
if (!(obj instanceof com.ORM.SbdWorkerTab)) return false;
else {
com.ORM.SbdWorkerTab sbdWorkerTab = (com.ORM.SbdWorkerTab) obj;
if (null == this.getId() || null == sbdWorkerTab.getId()) return false;
else return (this.getId().equals(sbdWorkerTab.getId()));
}
}
public int hashCode () {
if (Integer.MIN_VALUE == this.hashCode) {
if (null == this.getId()) return super.hashCode();
else {
String hashStr = this.getClass().getName() + ":" + this.getId().hashCode();
this.hashCode = hashStr.hashCode();
}
}
return this.hashCode;
}
public String toString () {
return super.toString();
}
}
下面是SWT的界面代码
MudifyUI
package com.ui;
import org.eclipse.swt.widgets.Dialog;
public class MudifyUI extends Dialog {
protected Object result;
protected Shell shell;
private Text text;
private Text text_1;
private Text text_2;
private Text text_3;
private SbdWorkerTab sbdWorkerTab;
/**
* Create the dialog.
*
* @param parent
* @param style
*/
public MudifyUI(Shell parent, int style, SbdWorkerTab sbdWorkerTab) {
super(parent, style);
this.sbdWorkerTab = sbdWorkerTab;
setText("SWT Dialog");
}
/**
* Open the dialog.
*
* @return the result
*/
public Object open() {
createContents();
shell.open();
shell.layout();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return result;
}
/**
* Create contents of the dialog.
*/
private void createContents() {
shell = new Shell(getParent(), SWT.CLOSE | SWT.MIN | SWT.TITLE
| SWT.APPLICATION_MODAL);
shell.setSize(337, 177);
shell.setText(getText());
shell.setLayout(new FillLayout(SWT.HORIZONTAL));
{
Composite composite = new Composite(shell, SWT.NONE);
composite.setLayout(new GridLayout(3, false));
{
System.out.println("实体对象中的工号为:" + sbdWorkerTab.getId());
}
new Label(composite, SWT.NONE);
{
Label label = new Label(composite, SWT.RIGHT);
label.setText("工号:");
}
text = new Text(composite, SWT.BORDER);
GridData gd_text = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
gd_text.widthHint = 144;
text.setLayoutData(gd_text);
text.setEditable(false);
text.setText(sbdWorkerTab.getId());
new Label(composite, SWT.NONE);
{
Label label = new Label(composite, SWT.RIGHT);
label.setText("姓名:");
}
{
text_1 = new Text(composite, SWT.BORDER);
GridData gd_text_1 = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
gd_text_1.widthHint = 223;
text_1.setLayoutData(gd_text_1);
text_1.setText(sbdWorkerTab.getWorkerName());
}
new Label(composite, SWT.NONE);
{
Label label = new Label(composite, SWT.RIGHT);
label.setText("密码:");
}
{
text_2 = new Text(composite, SWT.BORDER);
text_2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
text_2.setText(sbdWorkerTab.getWorkerPassword());
}
new Label(composite, SWT.NONE);
{
Label label = new Label(composite, SWT.RIGHT);
label.setText("工作角色:");
}
{
text_3 = new Text(composite, SWT.BORDER);
text_3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
text_3.setText(sbdWorkerTab.getWorkerRole());
}
new Label(composite, SWT.NONE);
{
Button button = new Button(composite, SWT.NONE);
button.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shell.dispose();
}
});
button.setText("取消");
}
{
Button button = new Button(composite, SWT.NONE);
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sbdWorkerTab = new SbdWorkerTab();
sbdWorkerTab.setId(text.getText());
sbdWorkerTab.setWorkerName(text_1.getText());
sbdWorkerTab.setWorkerPassword(text_2.getText());
sbdWorkerTab.setWorkerRole(text_3.getText());
RegisterDao registerDao = new RegisterDao();
registerDao.updateWorker(sbdWorkerTab);
shell.dispose();
}
});
button.setText("更新");
}
}
}
}
RegistertUI
package com.ui;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import com.ORM.SbdWorkerTab;
import com.dao.RegisterDao;
public class RegistertUI {
protected Shell shell;
private Text idText;
private Text nameText;
private Text passText;
public static void main(String[] args) {
try {
RegistertUI window = new RegistertUI();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(386, 264);
shell.setText("SWT Application");
shell.setLayout(new FillLayout(SWT.HORIZONTAL));
Composite composite = new Composite(shell, SWT.NONE);
Label label = new Label(composite, SWT.NONE);
label.setBounds(64, 39, 49, 13);
label.setText("\u5DE5\u53F7");
idText = new Text(composite, SWT.BORDER);
idText.setBounds(138, 33, 139, 19);
Label label_1 = new Label(composite, SWT.NONE);
label_1.setBounds(64, 73, 49, 13);
label_1.setText("\u59D3\u540D");
nameText = new Text(composite, SWT.BORDER);
nameText.setBounds(138, 67, 139, 19);
Label label_2 = new Label(composite, SWT.NONE);
label_2.setBounds(64, 108, 49, 13);
label_2.setText("\u5BC6\u7801");
passText = new Text(composite, SWT.BORDER);
passText.setBounds(138, 102, 139, 19);
Button button = new Button(composite, SWT.NONE);
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String id = idText.getText();
String name = nameText.getText();
String password = passText.getText();
SbdWorkerTab sbdWorkerTab = new SbdWorkerTab();
sbdWorkerTab.setId(id);
sbdWorkerTab.setWorkerName(name);
sbdWorkerTab.setWorkerPassword(password);
sbdWorkerTab.setWorkerRole("Hibernate C/S1");
RegisterDao dao = new RegisterDao();
dao.addWorker(sbdWorkerTab);
}
});
button.setBounds(116, 151, 68, 23);
button.setText("\u63D0\u4EA4");
Button button_1 = new Button(composite, SWT.NONE);
button_1.setBounds(193, 151, 68, 23);
button_1.setText("\u53D6\u6D88");
}
}
ShowInfoUI
package com.ui;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.layout.grouplayout.GroupLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import com.ORM.SbdWorkerTab;
import com.dao.RegisterDao;
public class ShowInfoUI {
protected Shell shell;
private Table table;
private SbdWorkerTab sbdWorkerTab = new SbdWorkerTab();
private String workerId = "";
/**
* Launch the application.
*
* @param args
*/
public static void main(String[] args) {
try {
ShowInfoUI window = new ShowInfoUI();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(527, 364);
shell.setText("SWT Application");
shell.setLayout(new FillLayout(SWT.HORIZONTAL));
Composite composite = new Composite(shell, SWT.NONE);
table = new Table(composite, SWT.BORDER | SWT.CHECK
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
table.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
TableItem[] tableItems = table.getSelection();
workerId = tableItems[0].getText(0);
sbdWorkerTab.setId(tableItems[0].getText(0));
sbdWorkerTab.setWorkerName(tableItems[0].getText(1));
sbdWorkerTab.setWorkerPassword(tableItems[0].getText(2));
sbdWorkerTab.setWorkerRole(tableItems[0].getText(3));
System.out.println(sbdWorkerTab.getId());
System.out.println(sbdWorkerTab.getWorkerName());
System.out.println(sbdWorkerTab.getWorkerPassword());
System.out.println(sbdWorkerTab.getWorkerRole());
MudifyUI mudifyUI = new MudifyUI(shell, SWT.NONE, sbdWorkerTab);
mudifyUI.open();
}
});
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn tableColumn = new TableColumn(table, SWT.CENTER);
tableColumn.setWidth(100);
tableColumn.setText("\u5DE5\u53F7");
TableColumn tableColumn_1 = new TableColumn(table, SWT.LEFT);
tableColumn_1.setWidth(100);
tableColumn_1.setText("\u59D3\u540D");
TableColumn tableColumn_2 = new TableColumn(table, SWT.LEFT);
tableColumn_2.setWidth(100);
tableColumn_2.setText("\u5BC6\u7801");
TableColumn tableColumn_3 = new TableColumn(table, SWT.LEFT);
tableColumn_3.setWidth(100);
tableColumn_3.setText("\u89D2\u8272");
Button button = new Button(composite, SWT.NONE);
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
table.setItemCount(0);
List<SbdWorkerTab> workerList = new ArrayList<SbdWorkerTab>();
workerList = (new RegisterDao()).listWorker();
if (workerList != null && workerList.size() > 0) {
for (int i = 0; i < workerList.size(); i++) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[]{workerList.get(i).getId(),
workerList.get(i).getWorkerName(),
workerList.get(i).getWorkerPassword(),
workerList.get(i).getWorkerRole()});
}
}
}
});
button.setText("\u663E\u793A\u4FE1\u606F");
Button button_1 = new Button(composite, SWT.NONE);
button_1.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
RegisterDao registerDao = new RegisterDao();
if (workerId != null && !workerId.equals("")) {
registerDao.deleteWorker(workerId);
}
}
});
button_1.setText("删除信息");
GroupLayout gl_composite = new GroupLayout(composite);
gl_composite
.setHorizontalGroup(gl_composite.createParallelGroup(
GroupLayout.LEADING).add(
gl_composite.createSequentialGroup().add(77)
.add(button).add(32).add(button_1)
.addContainerGap(278, Short.MAX_VALUE)).add(
gl_composite.createSequentialGroup().add(5).add(table,
GroupLayout.DEFAULT_SIZE, 508, Short.MAX_VALUE)
.add(6)));
gl_composite.setVerticalGroup(gl_composite.createParallelGroup(
GroupLayout.TRAILING).add(
gl_composite.createSequentialGroup().addContainerGap().add(
table, GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
.add(18).add(
gl_composite.createParallelGroup(
GroupLayout.BASELINE).add(button).add(
button_1)).addContainerGap()));
composite.setLayout(gl_composite);
}
}
下面是运行效果:
更新过后的工程源代码下载地址:http://download.csdn.net/detail/captaingan/8346195
以前旧的工程代码我将删除掉。
多谢大家阅读我的这篇博客,很久以前都想修改这篇博客,4年后的今天,2015年,才来完善这个文章,抱歉。哈哈。