- <?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>
- <!-- Database connection settings -->
- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="connection.url">jdbc:mysql://localhost:3306/ehome</property>
- <property name="connection.username">root</property>
- <property name="connection.password">mysql</property>
- <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
- <property name="current_session_context_class">thread</property>
- <property name="show_sql">true</property>
- <mapping resource="org/bkgd/ehome/jeeplugin/userapp/domain/HhArticle.hbm.xml" />
- </session-factory>
- </hibernate-configuration>
HhArticle.hbm.xml 文件在此省略
编写HibernateUtil辅助类 获取sessionFactory
[java] view plaincopy
- public class HibernateUtils {
- private static final SessionFactory sessionFactory;;
- //创建sessionFactory
- static {
- try {
- sessionFactory = 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;
- }
- }
测试类
[java] view plaincopy
- public class TestPersister {
- private static AbstractEntityPersister classMetadata;
- private Object obj;
- public TestPersister(SessionFactory sessionFatory, Object obj) {
- classMetadata = (AbstractEntityPersister) sessionFatory.getClassMetadata(obj.getClass());
- this.obj = obj;
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- //实例化classMetadata 传入sessionFactory和obj对象
- TestPersister tp = new TestPersister(HibernateUtils.getSessionFactory(),new HhArticle());
- Session session = HibernateUtils.getSessionFactory().getCurrentSession();
- session.beginTransaction();
- SQLQuery sqlquery = session.createSQLQuery("DELETE FROM " + classMetadata.getTableName());
- sqlquery.executeUpdate();
- session.getTransaction().commit(); //事务提交
- //classMetadata一些其他操作
- System.out.println(classMetadata.getTableName()); //表名
- System.out.println(classMetadata.getIdentifierPropertyName()); //主键列映射属性
- System.out.println(classMetadata.getEntityName()); //对象名称
- for(String str:classMetadata.getPropertyNames()){ //非主键属性
- System.out.println(str);
- }
- }
- public AbstractEntityPersister getClassMetadata() {
- return classMetadata;
- }
- public void setClassMetadata(AbstractEntityPersister classMetadata) {
- this.classMetadata = classMetadata;
- }
- public Object getObj() {
- return obj;
- }
- public void setObj(Object obj) {
- this.obj = obj;
- }
- }
时间: 2024-10-16 19:04:23