使用Hibernate实现ORM
映射文件如下:<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="test_hibernate.user" table="user"> <id name="id" column="id" type="int"> </id> <property name="name" column="name" type="string" not-null="true"/>
<property name="age" column="age" type="int" not-null="true"/> </class></hibernate-mapping>
映射文件如下:<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="test_hibernate.user" table="user"> <id name="id" column="id" type="int"> </id> <property name="name" column="name" type="string" not-null="true"/>
<property name="age" column="age" type="int" not-null="true"/> </class></hibernate-mapping>
hibernate.connection.driver_class=com.microsoft.jdbc.sqlserver.SQLServerDriver
hibernate.connection.url=jdbc:microsoft:sqlserver://xxx.xxx.xx.xx:1433;DatabaseName=test
hibernate.connection.username=sa
hibernate.connection.password=
hibernate.show_sql=true程序文件如下:import org.hibernate.*;
import org.hibernate.cfg.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;public class userService{
public static SessionFactory sessionFactory;
static{
try{
// Create a configuration based on the properties file we've put
// in the standard place.
Configuration config = new Configuration();
config.addClass(user.class);
// Get the session factory we can use for persistence
sessionFactory = config.buildSessionFactory();
System.out.println("in the static place!");
}catch(Exception e){e.printStackTrace();}
}public boolean saveUser(user user) throws Exception{
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(user);
tx.commit();
}catch (Exception e) {
if (tx != null) {
tx.rollback();
return false;
}
throw e;
} finally {
session.close();
}
return true;
}
}
<id name="id" column="id" type="long">
<generator class="identity"/>
</id>还有,楼主的类名最好用大写字母开头,对象名最好不要和类名一样,很难维护而且容易出错
建议,还有user可以用,不是关键字,我用过的
问题已经解决,正如wengzuliang(Jeff)所说的那样,user是sql server的关键字。谢谢!
同时,感谢yinleiyoung(星际孤虹)关于代码规范的建议!