Hibernate 또는 JDBC
25 개의 테이블과 ~ 15 개의 JInternalFrames (테이블에 대한 데이터 입력 양식)의 스키마가있는 씩 클라이언트, Java 스윙 응용 프로그램이 있습니다. DBMS 상호 작용을 위해 직선 JDBC 또는 ORM (이 경우 스프링 프레임 워크를 사용하여 최대 절전 모드) 중 하나를 선택해야합니다. 응용 프로그램에서 빌드는 앞으로 발생할 것입니다.
이 크기의 프로젝트에서 최대 절전 모드가 과도하게 작동합니까? 예 또는 아니오 답변에 대한 설명은 많은 도움이 될 것입니다 (또는 보증되는 경우 다른 접근 방식).
TIA.
단 하나의 간단한 대답이없는 좋은 질문입니다.
저는 Hibernate를 여러 해에 걸쳐 여러 프로젝트에서 사용한 후 열렬한 팬이었습니다. 나는 모든 프로젝트가 기본적으로 최대 절전 모드로 설정되어야한다고 믿었습니다.
오늘은 잘 모르겠습니다.
Hibernate (및 JPA)는 특히 개발주기 초기에 일부 기능에 적합합니다. JDBC를 사용하는 것보다 Hibernate로 작업하는 것이 훨씬 빠릅니다. 캐싱, 낙관적 잠금 등 많은 기능을 무료로 사용할 수 있습니다.
반면에 숨겨진 비용이 있습니다. Hibernate는 시작할 때 매우 간단합니다 . 튜토리얼을 따라하고 클래스에 주석을 달면 끈기가 있습니다. 그러나 그것은 간단하지 않으며 좋은 코드를 작성할 수 있으려면 내부 작업과 데이터베이스 디자인에 대한 이해가 필요합니다. 막 시작하는 경우 나중에 물릴 수있는 몇 가지 문제를 인식하지 못할 수 있으므로 여기에 불완전한 목록이 있습니다.
공연
런타임 성능은 충분하지만 아직 최대 절전 모드가 프로덕션 성능 저하의 원인 인 상황을 보지 못했습니다 . 문제는 시작 성능과 이것이 단위 테스트 시간과 개발 성능에 미치는 영향입니다. 최대 절전 모드가로드되면 모든 엔티티를 분석하고 많은 사전 캐싱을 수행합니다. 규모가 크지 않은 애플리케이션의 경우 약 5-10-15 초가 소요될 수 있습니다. 이제 1 초 단위 테스트에 11 초가 걸립니다. 재미 없어.
데이터베이스 독립성
데이터베이스에서 미세 조정을 수행 할 필요가없는 한 매우 멋집니다.
인 메모리 세션
모든 트랜잭션에 대해 Hibernate는 "접촉하는"모든 데이터베이스 행에 대해 메모리에 객체를 저장합니다. 간단한 데이터 입력을 할 때 좋은 최적화입니다. 하지만 어떤 이유로 많은 개체를 처리해야하는 경우 직접 메모리 내 세션을 명시적이고 신중하게 정리하지 않는 한 성능에 심각한 영향을 미칠 수 있습니다.
캐스케이드
캐스케이드를 사용하면 개체 그래프 작업을 단순화 할 수 있습니다. 예를 들어 루트 객체와 일부 자식이 있고 루트 객체를 저장하는 경우 자식도 저장하도록 최대 절전 모드를 구성 할 수 있습니다. 개체 그래프가 복잡해지면 문제가 시작됩니다. 당신이 극도로 조심스럽고 내부적으로 무슨 일이 일어나는지 잘 이해하지 않는다면, 이것을 엉망으로 만들기 쉽습니다. 그리고 그렇게 할 때 이러한 문제를 디버깅하는 것은 매우 어렵습니다.
지연 로딩
지연로드는 개체를로드 할 때마다 최대 절전 모드가 관련 개체를 모두로드하지 않고 대신 액세스를 시도하자마자 해결되는 자리 표시자를 제공한다는 것을 의미합니다. 훌륭한 최적화 맞습니까? 이 동작을 인식해야하는 경우를 제외하고는 알 수없는 오류가 발생합니다. 예를 들어 Google "LazyInitializationException". 그리고 성능에주의하십시오. 개체와 개체 그래프를로드하는 순서에 따라 "n + 1 selects problem"을 누를 수 있습니다. 자세한 내용은 Google에서 확인하세요.
스키마 업그레이드
Hibernate는 자바 코드를 리팩토링하고 다시 시작함으로써 쉬운 스키마 변경을 허용합니다. 시작할 때 좋습니다. 하지만 버전 1을 출시합니다. 그리고 고객을 잃고 싶지 않다면 스키마 업그레이드 스크립트를 제공해야합니다. 이는 모든 스키마 변경이 SQL에서 수행되어야하므로 더 이상 단순한 리팩토링이 없음을 의미합니다.
보기 및 저장 프로 시저
Hibernate는 작업하는 데이터에 대한 독점적 인 쓰기 액세스가 필요합니다. 즉, 뷰, 저장 프로 시저 및 트리거는 인식하지 못하는 최대 절전 모드로 데이터를 변경할 수 있으므로 실제로 사용할 수 없습니다. 별도의 트랜잭션에서 데이터베이스에 데이터를 쓰는 일부 외부 프로세스가있을 수 있습니다. 그러나 그렇게하면 캐시에 잘못된 데이터가 있습니다. 한 가지 더 신경 써야합니다.
단일 스레드 세션
Hibernate 세션은 단일 스레드입니다. 세션을 통해로드 된 모든 개체는 동일한 스레드에서만 액세스 (읽기 포함) 할 수 있습니다. 이것은 서버 측 응용 프로그램에 허용되지만 GUI 기반 응용 프로그램을 수행하는 경우 불필요한 일을 복잡하게 만들 수 있습니다.
내 요점은 무료 식사가 없다는 것입니다.
Hibernate는 좋은 도구이지만 복잡한 도구이며 제대로 이해하려면 시간이 필요합니다. 귀하 또는 귀하의 팀원이 그러한 지식을 가지고 있지 않다면 단일 애플리케이션에 대해 순수 JDBC (또는 Spring JDBC)를 사용하는 것이 더 간단하고 빠를 수 있습니다. 반면에 미래보다 학습 (수행 및 디버깅을 통한 학습 포함)에 시간을 투자 할 의향이 있다면 장단점을 더 잘 이해할 수있을 것입니다.
Hibernate는 좋을 수 있지만 다른 JPA ORM은 데이터베이스 구조를 어느 정도 지시하는 경향이 있습니다. 예를 들어, 복합 기본 키는 Hibernate / JPA에서 수행 할 수 있지만 약간 어색합니다. 다른 예가 있습니다.
SQL에 익숙하다면 Ibatis를 살펴볼 것을 강력히 제안합니다 . Hibernate가 할 수있는 것의 90 % 이상을 수행 할 수 있지만 구현이 훨씬 간단합니다.
Ibatis보다 스트레이트 JDBC (또는 심지어 Spring JDBC)를 선택한 이유는 하나도 생각할 수 없습니다. Hibernate는 더 복잡한 선택입니다.
Spring 및 Ibatis Tutorial을 살펴보십시오 .
의심 할 여지없이 Hibernate에는 복잡성이 있습니다.
그러나 내가 Hibernate 접근법에 대해 정말 좋아하는 것은 (다른 것들도 역시) 자바에서 얻을 수있는 개념적 모델이 더 낫다는 것입니다. 나는 OO를 만병 통치약으로 생각하지 않고 디자인의 이론적 순수성을 찾지는 않지만 OO가 실제로 내 코드를 단순화하는 것을 너무 많이 발견했습니다. 세부 사항을 구체적으로 요청 하셨듯이 다음은 몇 가지 예입니다.
복잡성은 모델에없는 및 단체하지만, 예를 들어 모든 엔티티를 조작하여 프레임 워크이다. 관리자에게 어려운 부분은 몇 가지 프레임 워크 클래스가 아니라 모델이므로 Hibernate를 사용하면 어려운 부분 (모델)을 가장 깨끗하게 유지할 수 있습니다.
필드 (예 : ID 또는 감사 필드 등)가 모든 엔터티에서 사용되는 경우이를 사용하여 수퍼 클래스 를 만들 수 있습니다 . 따라서 :
- 적은 코드를 작성하지만 더 중요한 것은 ...
- 모델에 개념이 적습니다 (고유 한 개념은 코드에서 고유함).
- 무료로 엔티티 (알 수 없음, 유형 전환 또는 캐스트 없음)와 함께 제공되는보다 일반적인 코드를 작성하면 ID에 액세스 할 수 있습니다.
Hibernate는 또한 당신이 필요로 할 수있는 다른 모델 caracteristics를 처리 할 수있는 많은 기능을 가지고 있습니다 (지금 또는 나중에 필요에 따라 추가하십시오). 디자인 의 확장 성 품질 로 간주 하십시오.
- 상속 (서브 클래 싱)을 컴포지션 (여러 엔터티에 필요한 몇 가지 관련 필드를 포함하는 동일한 구성원을 가진 여러 엔터티)으로 대체 할 수 있습니다.
- There can be inheritance between a few of your entities. It often happens that you have two tables that have pretty much the same structure (but you don't want to store all data in one table, because you would loose referential integrity to a different parent table).
With reuse between your entities (but only appropriate inheritance, and composition), there is usually some additional advantages to come. Examples :
- there is often some way to read the data of the entities that is similar but different. Suppose I read the "title" field for three entities, but for some I replace the result with a differing default value if it is null. It is easy to have a signature "getActualTitle" (in a superclass or an interface), and implement the default value handling in the three implementations. That means the code out of my entities just deals with the concept of an "actual title" (I made this functional concept explicit), and the method inheritance takes care of executing the correct code (no more switch or if, no code duplication).
- ...
Over time, the requirements evolve. There will be a point where your database structure has problems. With JDBC alone, any change to the database must impact the code (ie. double cost). With Hibernate, many changes can be absorbed by changing only the mapping, not the code. The same happens the other way around : Hibernate lets you change your code (between versions for example) without altering your database (changing the mapping, although it is not always sufficient). To summarize, Hibernate lets your evolve your database and your code independtly.
For all these reasons, I would choose Hibernate :-)
I think either is a fine choice, but personally I would use hibernate. I don't think hibernate is overkill for a project of that size.
Where Hibernate really shines for me is dealing with relationships between entities/tables. Doing JDBC by hand can take a lot of code if you deal with modifying parent and children (grandchildren, siblings, etc) at the same time. Hibernate can make this a breeze (often a single save of the parent entity is enough).
There are certainly complexities when dealing with Hibernate though, such as understanding how the Session flushing works, and dealing with lazy loading.
Straight JDBC would fit the simplest cases at best.
If you want to stay within Java and OOD then going Hibernate or Hibernate/JPA or any-other-JPA-provider/JPA should be your choice.
If you are more comfortable with SQL then having Spring for JDBC templates and other SQL-oriented frameworks won't hurt.
In contrast, besides transactional control, there is not much help from having Spring when working with JPA.
Hibernate best suits for the middleware applications. Assume that we build a middle ware on top of the data base, The middelware is accessed by around 20 applications in that case we can have a hibernate which satisfies the requirement of all 20 applications.
In JDBC, if we open a database connection we need to write in try, and if any exceptions occurred catch block will takers about it, and finally used to close the connections.
In jdbc all exceptions are checked exceptions, so we must write code in try, catch and throws, but in hibernate we only have Un-checked exceptions
Here as a programmer we must close the connection, or we may get a chance to get our of connections message…!
Actually if we didn’t close the connection in the finally block, then jdbc doesn’t responsible to close that connection.
In JDBC we need to write Sql commands in various places, after the program has created if the table structure is modified then the JDBC program doesn’t work, again we need to modify and compile and re-deploy required, which is tedious.
JDBC used to generate database related error codes if an exception will occurs, but java programmers are unknown about this error codes right.
While we are inserting any record, if we don’t have any particular table in the database, JDBC will rises an error like “View not exist”, and throws exception, but in case of hibernate, if it not found any table in the database this will create the table for us
JDBC support LAZY loading and Hibernate supports Eager loading
Hibernate supports Inheritance, Associations, Collections
In hibernate if we save the derived class object, then its base class object will also be stored into the database, it means hibernate supporting inheritance
Hibernate supports relationships like One-To-Many,One-To-One, Many-To- Many-to-Many, Many-To-One
Hibernate supports caching mechanism by this, the number of round trips between an application and the database will be reduced, by using this caching technique an application performance will be increased automatically
Getting pagination in hibernate is quite simple.
Hibernate has capability to generate primary keys automatically while we are storing the records into database
... In-memory Session ... LazyInitializationException ...
You could look at Ebean ORM which doesn't use session objects ... and where lazy loading just works. Certainly an option, not overkill, and will be simpler to understand.
if billions of user using out app or web then in jdbc query will get executed billions of time but in hibernate query will get executed only once for any number of user most important and easy advantage of hibernate over jdbc.
참고URL : https://stackoverflow.com/questions/1353137/hibernate-or-jdbc
'program story' 카테고리의 다른 글
| 레일에 link_to ruby로 매개 변수 전달 (0) | 2020.11.06 |
|---|---|
| 장난감 프로젝트에 설정하고 사용하기 가장 쉬운 버전 관리 시스템은 무엇입니까? (0) | 2020.11.06 |
| Android Emulator의 IP 주소를 얻는 방법은 무엇입니까? (0) | 2020.11.06 |
| 로그인 실패로 인해 SQL Server 2012를 시작할 수 없습니다. (0) | 2020.11.06 |
| Ubuntu 12.04에서 Python.h 누락 (0) | 2020.11.06 |