2014-11-28 15 views
5


Trong ứng dụng của tôi, tôi sử dụng Hibernate với cơ sở dữ liệu SQL Server, vì vậy tôi đặtLàm thế nào để có được Hibernate phương ngữ trong thời gian chạy

<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"> 

trong persistence.xml tôi.

Trong một số trường hợp, tôi muốn sắp xếp bản ghi với NULL bao gồm, tôi sử dụng từ khóa NULLS FIRST.
Bởi vì nó không được hỗ trợ theo mặc định bởi CriteriaQuery/CriteriaBuilder trong Hibernate, sau đó tôi sử dụng Interceptor để sửa đổi truy vấn gốc.
Vấn đề là, NULLS khóa FIRST không được hỗ trợ trong SQL Server, vì vậy tôi sử dụng từ khoá:

case when column_name is null then 0 else 1 end, column_name 

Nếu tôi muốn di chuyển cơ sở dữ liệu từ SQL Server để Oracle (ví dụ), sau đó tôi cần phải đặt nếu -trên trong Interceptor của tôi, chọn phương ngữ mà tôi đang sử dụng, đúng không?

Đây là cách tôi minh họa cho họ:

String dialect = .............. 
if (dialect.equals("org.hibernate.dialect.SQLServerDialect")) { // get SQL Server dialect 
    // put keyword "case when column_name is null then 0 else 1 end, column_name" 
} else { 
    // put keyword "NULLS FIRST/LAST" 
} 

Làm thế nào tôi có thể nhận được các cấu hình phương ngữ (trong persistence.xml) trong thời gian chạy?

+0

một liên kết về từ khóa NULLS FIRST: https://hibernate.atlassian.net/browse/HHH-465 – danisupr4

+0

tôi sử dụng Interceptor dựa trên bài viết này: http://stackoverflow.com/questions/3683174/hibernate- order-by-with-nulls-last – danisupr4

+0

Các liên kết này có thể giúp bạn lấy thông tin phương ngữ từ SessionFactory; [link1] (http://stackoverflow.com/questions/1571928/retrieve-auto-detected-hibernate-dialect) và [link2] (http://stackoverflow.com/questions/8742617/resolve-sql-dialect-using -hibernate) –

Trả lời

0

Nếu bạn sử dụng Spring + ngủ đông, hãy thử này

@[email protected]("sessionFactory") org.springframework.orm.hibernate3.LocalSessionFactoryBean sessionFactory; //Suppose using hibernate 3 

và trong phương pháp của bạn:

sessionFactory.getHibernateProperties().get("hibernate.dialect") 
0

Tôi đã tìm thấy câu trả lời từ bài này: Resolve SQL dialect using hibernate

Cảm ơn bạn đã @ Dewfy,

đây là giải pháp:

//take from current EntityManager current DB Session 
Session session = (Session) em.getDelegate(); 
//Hibernate's SessionFactoryImpl has property 'getDialect', to 
//access this I'm using property accessor: 
Object dialect = 
     org.apache.commons.beanutils.PropertyUtils.getProperty(
      session.getSessionFactory(), "dialect"); 
//now this object can be casted to readable string: 
if (dialect.toString().equals("org.hibernate.dialect.SQLServerDialect")) { 

} else { 

} 
Các vấn đề liên quan