development

ORM을 사용하지 않는 이유가 있습니까?

big-blog 2020. 8. 15. 09:51
반응형

ORM을 사용하지 않는 이유가 있습니까? [닫은]


견습 기간 동안 저는 주로 제가 직접 코딩하고 디자인 한 소규모 프로젝트에 NHibernate사용했습니다 . 이제 더 큰 프로젝트를 시작하기 전에 데이터 액세스를 설계하는 방법과 ORM 레이어 사용 여부에 대해 논의했습니다. 나는 여전히 견습생이고 여전히 엔터프라이즈 프로그래밍의 초보자라고 생각하기 때문에 데이터베이스에 대한 객체 관계형 매퍼를 사용하면 개발을 상당히 쉽게 할 수 있다는 내 의견으로는 실제로 추진하려고하지 않았습니다. 개발팀의 다른 코더들은 저보다 훨씬 더 경험이 많기 때문에 그들이 말하는 대로만 할 것 같습니다. :-)

그러나 NHibernate 또는 유사한 프로젝트를 사용하지 않는 두 가지 주요 이유를 완전히 이해하지 못합니다.

  1. SQL 쿼리를 사용하여 자신의 데이터 액세스 개체를 만들고 Microsoft SQL Server Management Studio에서 이러한 쿼리를 복사 할 수 있습니다.
  2. ORM 디버깅은 어려울 수 있습니다.

따라서 물론 많은 SELECTs 등으로 데이터 액세스 계층을 구축 할 수 있지만 여기서는 자동 조인, 지연로드 프록시 클래스 및 테이블이 새 열을 얻거나 열이 발생하는 경우 유지 관리 노력이 줄어드는 이점을 놓칩니다. 이름이 변경되었습니다. (다수의 업데이트 SELECT, INSERTUPDATE매핑 설정을 업데이트 할 가능성이 비즈니스 클래스와 DTO들 리팩토링 대 쿼리.)

또한 NHibernate를 사용하면 프레임 워크를 잘 모르면 예기치 않은 문제가 발생할 수 있습니다. 예를 들어 자동으로 유효성을 검사 할 문자열의 길이를 설정 한 Table.hbm.xml을 신뢰하는 것이 될 수 있습니다. 그러나 "간단한"SqlConnection 쿼리 기반 데이터 액세스 계층에서 유사한 버그를 상상할 수도 있습니다.

마지막으로, 위에서 언급 한 주장이 중요한 데이터베이스 기반 엔터프라이즈 애플리케이션에 ORM을 사용하지 않는 좋은 이유입니까? 그들이 놓친 다른 주장이 있습니까?

(나는 이것이 팀워크가 필요한 최초의 "대형".NET / C # 기반 애플리케이션이라고 생각한다고 덧붙여 야 할 것입니다. 단위 테스트 또는 지속적인 통합과 같이 Stack Overflow에서 매우 평범한 것으로 보이는 모범 사례는 그렇지 않습니다. -지금까지 여기에 존재합니다.)


최근 몇 년 동안 ORM이 폭발적으로 성장하고 있으며 경험이 많은 동료들은 여전히 ​​"모든 데이터베이스 호출이 저장 프로 시저를 통해 이루어져야한다"는 생각을하고있을 수 있습니다.

ORM이 디버깅을 더 어렵게 만드는 이유는 무엇입니까? 저장된 proc 또는 ORM에서 가져온 것과 동일한 결과를 얻을 수 있습니다.

제가 ORM에 대해 생각할 수있는 유일한 진짜 단점은 보안 모델이 약간 덜 유연하다는 것입니다.

편집 : 귀하의 질문을 다시 읽었으며 쿼리를 인라인 SQL에 복사하여 붙여 넣는 것 같습니다. 이로 인해 보안 모델이 ORM과 동일 해 지므로 ORM에 비해이 접근 방식보다 이점이 전혀 없습니다. 매개 변수화되지 않은 쿼리를 사용하는 경우 실제로 보안 위험이 있습니다.


짧은 대답은 그렇습니다. 정말 좋은 이유가 있습니다. 실제로 ORM을 사용할 수없는 경우가 있습니다.

예를 들어, 저는 대기업 금융 기관에서 일하고 있으며 많은 보안 지침을 따라야합니다. 우리에게 부과되는 규칙과 규정을 충족하기 위해 감사를 통과하는 유일한 방법은 저장 프로 시저 내에서 데이터 액세스를 유지하는 것입니다. 이제 어떤 사람들은 그것이 멍청하다고 말할지 모르지만 솔직히 그렇지 않습니다. ORM 도구를 사용하면 도구 / 개발자가 원하는 것을 삽입, 선택, 업데이트 또는 삭제할 수 있습니다. 저장 프로시 저는 특히 클라이언트 데이터를 처리하는 환경에서 훨씬 더 많은 보안을 제공합니다. 이것이 고려할 가장 큰 이유라고 생각합니다. 보안.


ORM의 스윗 스팟

ORM은 적용 가능한 쿼리의 95 % 이상을 자동화하는 데 유용합니다. 그들의 특별한 강점은 강력한 개체 모델 아키텍처와 그 개체 모델과 잘 어울리는 데이터베이스가있는 응용 프로그램이 있다는 것입니다. 새로운 빌드를하고 있고 팀에 강력한 모델링 기술이 있다면 ORM으로 좋은 결과를 얻을 수 있습니다.

손으로 더 잘 수행되는 몇 가지 쿼리가있을 수 있습니다. 이 경우이를 처리하기 위해 몇 가지 저장 프로 시저를 작성하는 것을 두려워하지 마십시오. 여러 DBMS 플랫폼에 앱을 이식하려는 경우에도 데이터베이스 종속 코드는 소수입니다. 지원하려는 플랫폼에서 애플리케이션을 테스트해야한다는 점을 염두에두고 일부 저장 프로 시저에 대한 약간의 추가 포팅 노력은 TCO에 큰 차이를 만들지 않습니다. 첫 번째 근사치로 98 %의 이식성은 100 %의 이식성과 동일하며 ORM의 한계를 극복하기 위해 복잡하거나 성능이 저조한 솔루션보다 훨씬 낫습니다.

저는 이전의 접근 방식이 매우 큰 (직원 수 100 년) J2EE 프로젝트에서 잘 작동하는 것을 보았습니다.

ORM이 가장 적합하지 않을 수있는 곳

다른 경우에는 ORM보다 응용 프로그램에 더 적합한 접근 방식이있을 수 있습니다. Fowler의 엔터프라이즈 애플리케이션 아키텍처 패턴에는 이에 대한 다양한 접근 방식을 카탈로그 화하는 데 상당히 좋은 작업을 수행하는 데이터 액세스 패턴에 대한 섹션이 있습니다. ORM이 적용되지 않을 수있는 상황에 대해 본 몇 가지 예는 다음과 같습니다.

  • 저장 프로 시저의 실질적인 레거시 코드 기반이있는 응용 프로그램에서 기능 지향 (기능 언어와 혼동하지 말 것) 데이터 액세스 계층을 사용하여 기존 sproc을 래핑 할 수 있습니다. 이렇게하면 기존 (따라서 테스트 및 디버깅 된) 데이터 액세스 계층 및 데이터베이스 디자인을 재사용 할 수 있습니다. 이는 종종 상당한 개발 및 테스트 노력을 나타내며 데이터를 새 데이터베이스 모델로 마이그레이션해야하는 시간을 줄여줍니다. 레거시 PL / SQL 코드베이스를 중심으로 Java 레이어를 래핑하거나 웹 인터페이스를 사용하여 리치 클라이언트 VB, Powerbuilder 또는 Delphi 앱을 대상으로 다시 지정하는 것은 종종 매우 좋은 방법입니다.

  • 변형은 OR 매핑에 반드시 적합하지 않은 데이터 모델을 상속하는 곳입니다. 예를 들어 외부 인터페이스에서 데이터를 채우거나 추출하는 인터페이스를 작성하는 경우 데이터베이스를 사용하는 것이 더 나을 수 있습니다.

  • 특히 2 단계 커밋으로 복잡한 분산 트랜잭션을 사용하는 경우 시스템 간 데이터 무결성이 중요한 금융 응용 프로그램 또는 기타 유형의 시스템입니다. ORM이 지원할 수있는 것보다 트랜잭션을 더 잘 관리해야 할 수도 있습니다.

  • 실제로 데이터베이스 액세스를 조정하려는 고성능 애플리케이션. 이 경우 낮은 수준에서 작업하는 것이 좋습니다.

  • ADO.Net과 같은 기존 데이터 액세스 메커니즘을 사용하는 상황에서 '충분히 훌륭하고'플랫폼을 잘 활용하는 것은 ORM이 가져 오는 것보다 더 큰 이점입니다.

  • 때로는 데이터가 데이터 일 수 있습니다. 예를 들어 애플리케이션이 '객체'가 아닌 '트랜잭션'으로 작업하고 있고 이것이 도메인에 대한 합리적인보기 일 수 있습니다. 이에 대한 예는 구성 가능한 분석 필드가있는 트랜잭션이있는 재무 패키지 일 수 있습니다. 애플리케이션 자체는 OO 플랫폼에 구축 될 수 있지만 단일 비즈니스 도메인 모델에 묶여 있지 않으며 GL 코드, 계정, 문서 유형 및 6 개 이상의 분석 필드를 인식하지 못할 수 있습니다. 이 경우 애플리케이션은 비즈니스 도메인 모델을 인식하지 못하며 개체 모델 (원장 구조 자체를 넘어서)은 애플리케이션과 관련이 없습니다.


우선-ORM을 사용한다고해서 코드를 테스트하기가 더 쉬워지지 않으며, 지속적인 통합 장면에서 반드시 이점을 제공하지도 않습니다.

제 경험상 ORM을 사용하면 개발 속도를 높일 수 있지만 해결해야 할 가장 큰 문제는 다음과 같습니다.

  1. 코드 테스트
  2. 코드 유지

이에 대한 해결책은 다음과 같습니다.

  1. 코드를 테스트 가능하게 만들기 ( SOLID 원칙 사용)
  2. 가능한 한 많은 코드에 대해 자동화 된 테스트 작성
  3. 가능한 한 자주 자동 테스트 실행

귀하의 질문에 대해, 귀하가 나열한 두 가지 반대는 다른 무엇보다 무지처럼 보입니다.

손으로 SELECT 쿼리를 작성할 수 없다는 것은 (이것이 복사-붙여 넣기가 필요한 이유라고 생각합니다) SQL 교육이 긴급하게 필요하다는 것을 나타냅니다.

ORM을 사용하지 않는 데에는 두 가지 이유가 있습니다.

  1. It is strictly forbidden by the company's policy (in which case I'd go work somewhere else)
  2. The project is extremely data intensive and using vendor specific solutions (like BulkInsert) makes more sense.

The usual rebuffs about ORMs (NHibernate in particular) are:

  1. Speed

    There is no reason why using an ORM would be any slower than hand coded Data Access. In fact, because of the caching and optimisations built into it, it can be quicker. A good ORM will produce a repeatable set of queries for which you can optimise your schema. A good ORM will also allow efficient retrieval of associated data using various fetching strategies.

  2. Complexity

    With regards to complexity, using an ORM means less code, which generally means less complexity. Many people using hand-written (or code generated) data access find themselves writing their own framework over "low-level" data access libraries (like writing helper methods for ADO.Net). These equate to more complexity, and, worse yet, they're rarely well documented, or well tested.
    If you are looking specifically at NHibernate, then tools like Fluent NHibernate and Linq To NHibernate also soften the learning curve.

The thing that gets me about the whole ORM debate is that the same people who claim that using an ORM will be too hard/slow/whatever are the very same people who are more than happy using Linq To Sql or Typed Datasets. Whilst the Linq To Sql is a big step in the right direction, it's still light years behind where some of the open source ORMs are. However, the frameworks for both Typed Datasets and for Linq To Sql is still hugely complex, and using them to go too far of the (Table=Class) + (basic CRUD) is stupidly difficult.

My advice is that if, at the end of the day, you can't get an ORM, then make sure that your data access is separated from the rest of the code, and that you you follow the Gang Of Four's advice of coding to an interface. Also, get a Dependancy Injection framework to do the wiring up.

(How's that for a rant?)


There are a wide range of common problems for which ORM tools like Hibernate are a god-send, and a few where it is a hindrance. I don't know enough about your project to know which it is.

One of Hibernate's strong points is that you get to say things only 3 times: every property is mentioned in the class, the .hbm.xml file, and the database. With SQL queries, your properties are in the class, the database, the select statements, the insert statements, the update statements, the delete statements, and all the marshalling and unmarshalling code supporting your SQL queries! This can get messy fast. On the other hand, you know how it works. You can debug it. It's all right there in your own persistence layer, not buried in the bowels of a 3rd party tool.

Hibernate could be a poster-child for Spolsky's Law of Leaky Abstractions. Get a little bit off the beaten path, and you need to know deep internal workings of the tool. It can be very annoying when you know you could have fixed the SQL in minutes, but instead you are spending hours trying to cajole your dang tool into generating reasonable SQL. Debugging is sometimes a nightmare, but it's hard to convince people who have not been there.

EDIT: You might want to look into iBatis.NET if they are not going to be turned around about NHibernate and they want control over their SQL queries.

EDIT 2: Here's the big red flag, though: "Good practices, which are seen as pretty normal on Stack Overflow, such as unit testing or continuous integration, are non-existing here up to now." So, these "experienced" developers, what are they experienced in developing? Their job security? It sounds like you might be among people who are not particularly interested in the field, so don't let them kill your interest. You need to be the balance. Put up a fight.


I worked on one project where not using an ORM was very successfully. It was a project that

  1. Had to be horizontally scalealbe from the start
  2. Had to be developed quickly
  3. Had a relatively simple domain model

The time that it would have taken to get NHibernate to work in a horizontally partitioned structure would have been much longer than the time that it took to develop a super simple datamapper that was aware of our partitioning scheme...

So, in 90% of projects that I have worked on an ORM has been an invaluable help. But there are some very specific circumstances where I can see not using an ORM as being best.


Let me first say that ORMs can make your development life easier if integrated properly, but there are a handful of problems where the ORM can actually prevent you from achieving your stated requirements and goals.

I have found that when designing systems that have heavy performance requirements that I am often challenged to find ways to make the system more performant. Many times, I end up with a solution that has a heavy write performance profile (meaning we're writing data a lot more than we're reading data). In these cases, I want to take advantage of the facilities the database platform offers to me in order to reach our performance goals (it's OLTP, not OLAP). So if I'm using SQL Server and I know I have a lot of data to write, why wouldn't I use a bulk insert... well, as you may have already discovered, most ORMS (I don't know if even a single one does) do not have the ability to take advantage of platform specific advantages like bulk insert.

You should know that you can blend the ORM and non-ORM techniques. I've just found that there are a handful of edge cases where ORMs can not support your requirements and you have to work around them for those cases.


For a non-trivial database based enterprise application, there really is no justifying not using an ORM.

Features aside:

  • By not using an ORM, you are solving a problem that has already solved repeatedly by large communities or companies with significant resources.
  • By using an ORM, the core piece of your data access layer benefits from the debugging efforts of that community or company.

To put some perspective in the argument, consider the advantages of using ADO.NET vs. writing the code to parse the tabular data stream oneself.

I have seen ignorance of how to use an ORM justify a developer's disdain for ORMs For example: eager loading (something I noticed you didn't mention). Imagine you want to retrieve a customer and all of their orders, and for those all of the order detail items. If you rely on lazy loading only, you will walk away from your ORM experience with the opinion: "ORMs are slow." If you learn how to use eager loading, you will do in 2 minutes with 5 lines of code, what your colleagues will take a half a day to implement: one query to the database and binding the results to a hierarchy of objects. Another example would be the pain of manually writing SQL queries to implement paging.

The possible exception to using an ORM would be if that application were an ORM framework designed to apply specialized business logic abstractions, and designed to be reused on multiple projects. Even if that were the case, however, you would get faster adoption by enhancing an existing ORM with those abstractions.

Do not let the experience of your senior team members drag you in the opposite direction of the evolution of computer science. I have been developing professionally for 23 years, and one of the constants is the disdain for the new by the old-school. ORMs are to SQL as the C language was to assembly, and you can bet that the equivalents to C++ and C# are on their way. One line of new-school code equals 20 lines of old-school.


When you need to update 50000000 records. Set a flag or whatever.

Try doing this using an ORM without calling a stored procedure or native SQL commands..

Update 1 : Try also retrieving one record with only a few of its fields. (When you have a very "wide" table). Or a scalar result. ORMs suck at this too.

UPDATE 2 : It seems that EF 5.0 beta promises batch updates but this is very hot news (2012, January)


I think that maybe when you work on bigger systems you can use a code generator tool like CodeSmith instead of a ORM... I recently found this: Cooperator Framework which generates SQL Server Stored Procedures and also generates your business entities, mappers, gateways, lazyload and all that stuff in C#...check it out...it was written by a team here in Argentina...

I think it's in the middle between coding the entire data access layer and use a ORM...


Personally, i have (until recently) opposed to use an ORM, and used to get by with writing a data access layer encapsulating all the SQL commands. The main objection to ORMs was that I didn't trust the ORM implementation to write exactly the right SQL. And, judging by the ORMs i used to see (mostly PHP libraries), i think i was totally right.

Now, most of my web development is using Django, and i found the included ORM really convenient, and since the data model is expressed first in their terms, and only later in SQL, it does work perfectly for my needs. I'm sure it wouldn't be too hard to outgrow it and need to supplement with hand-written SQL; but for CRUD access is more than enough.

I don't know about NHibernate; but i guess it's also "good enough" for most of what you need. But if other coders don't trust it; it will be a prime suspect on every data-related bug, making verification more tedious.

You could try to introduce it gradually in your workplace, focus first on small 'obvious' applications, like simple data access. After a while, it might be used on prototypes, and it might not be replaced...


If it is an OLAP database (e.g. static, read-only data used for reporting/analytics, etc.) then implementing an ORM framework is not appropriate. Instead, using the database's native data access functionality such as stored procedures would be preferable. ORMs are better suited for transactional (OLTP) systems.


I think there are many good reasons to not use an ORM. First and foremost, I'm a .NET developer and I like to stick within what the wonderful .NET framework has already provided to me. It does everything I possibly need it to. By doing this, you stay with a more standard approach, and thus there is a much better chance of any other developer working on the same project down the road being able to pick up what's there and run with it. The data access capabilities already provided by Microsoft are quite ample, there's no reason to discard them.

I've been a professional developer for 10 years, lead multiple very successful million+ dollar projects, and I have never once written an application that needed to be able to switch to any database. Why would you ever want a client to do this? Plan carefully, pick the right database for what you need, and stick with it. Personally SQL Server has been able to do anything I've ever needed to do. It's easy and it works great. There's even a free version that supports up to 10GB data. Oh, and it works awesome with .NET.

I have recently had to start working on several projects that use an ORM as the datalayer. I think it's bad, and something extra I had to learn how to use for no reason whatsoever. In the insanely rare circumstance the customer did need to change databases, I could have easily reworked the entire datalayer in less time than I've spent fooling with the ORM providers.

Honestly I think there is one real use for an ORM: If you're building an application like SAP that really does need the ability to run on multiple databases. Otherwise as a solution provider, I tell my clients this application is designed to run on this database and that is how it is. Once again, after 10 years and a countless number of applications, this has never been a problem.

Otherwise I think ORMs are for developers that don't understand less is more, and think the more cool 3rd party tools they use in their app, the better their app will be. I'll leave things like this to the die hard uber geeks while I crank out much more great software in the meantime that any developer can pick up and immediately be productive with.


Runtime performance is the only real downside I can think of but I think that's more than a fair trade-off for the time ORM saves you developing/testing/etc. And in most cases you should be able to locate data bottlenecks and alter your object structures to be more efficient.

I haven't used Hibernate before but one thing I have noticed with a few "off-the-shelf" ORM solutions is a lack of flexibility. I'm sure this depends on which you go with and what you need to do with it.


There are two aspects of ORMs that are worrisome. First, they are code written by someone else, sometimes closed source, sometimes open source but huge in scope. Second, they copy the data.

The first problem causes two issues. You are relying on outsiders code. We all do this, but the choice to do so should not be taken lightly. And what if it doesn't do what you need? When will you discover this? You live inside the box that your ORM draws for you.

The second problem is one of two phase commit. The relational database is being copied to a object model. You change the object model and it is supposed to update the database. This is a two phase commit and not the easiest thing to debug.


I suggest this reading for a list of the downsides of ORMs.

http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx

For my self, I've found ORMs very useful for most applications I've written!

/Asger


The experience I've had with Hibernate is that its semantics are subtle, and when there's problems, it's a bit hard to understand what's going wrong under the hood. I've heard from a friend that often one starts with Criteria, then needs a bit more flexibility and needs HQL, and later notices that after all, raw SQL is needed (for example, Hibernate doesn't have union AFAIK).

Also with ORM, people easily tend to overuse existing mappings/models, which leads to that there's an object with lots of attributes that aren't initiliazed. So after the query, inside transaction Hibernate makes additional data fetching, which leads to potential slow down. Also sadly, the hibernate model object is sometimes leaked into the view architecture layer, and then we see LazyInitializationExceptions.

To use ORM, one should really understand it. Unfortunately one gets easily impression that it's easy while it's not.


Not to be an answer per se, I want to rephrase a quote I've heard recently. "A good ORM is like a Yeti, everyone talks about one but no one sees it."

Whenever I put my hands on an ORM, I usually find myself struggling with the problems/limitations of that ORM. At the end, yes it does what I want and it was written somewhere in that lousy documentation but I find myself losing another hour I will never get. Anyone who used nhibernate, then fluent nhibernate on postgresql would understand what I've been thru. Constant feeling of "this code is not under my control" really sucks.

I don't point fingers or say they're bad, but I started thinking of what I'm giving away just to automate CRUD in a single expression. Nowadays I think I should use ORM's less, maybe create or find a solution that enables db operations at minimum. But it's just me. I believe some things are wrong in this ORM arena but I'm not skilled enough to express it what not.


I think that using an ORM is still a good idea. Especially considering the situation you give. It sounds by your post you are the more experienced when it comes to the db access strategies, and I would bring up using an ORM.

There is no argument for #1 as copying and pasting queries and hardcoding in text gives no flexibility, and for #2 most orm's will wrap the original exception, will allow tracing the queries generated, etc, so debugging isnt rocket science either.

As for validation, using an ORM will also usually allow much easier time developing validation strategies, on top of any built in validation.

Writing your own framework can be laborious, and often things get missed.

EDIT: I wanted to make one more point. If your company adopts an ORM strategy, that further enhances its value, as you will develop guidelines and practices for using and implementing and everyone will further enhance their knowledge of the framework chosen, mitigating one of the issues you brought up. Also, you will learn what works and what doesnt when situations arise, and in the end it will save lots of time and effort.


Every ORM, even a "good one", comes saddled with a certain number of assumptions that are related to the underlying mechanics that the software uses to pass data back and forth between your application layer and your data store.

I have found that for moderately sophisticated application, that working around those assumptions usually takes me more time than simply writing a more straightfoward solution such as: query the data, and manually instantiate new entities.

In particular, you are likely to run into hitches as soon as you employ multi-column keys or other moderately-complex relationships that fall just outside the scope of the handy examples that your ORM provided you when you downloaded the code.

I concede that for certain types of applications, particularly those that have a very large number of database tables, or dynamically-generated database tables, that the auto-magic process of an ORM can be useful.

Otherwise, to hell with ORMs. I now consider them to basically be a fad.

참고 URL : https://stackoverflow.com/questions/194147/are-there-good-reasons-not-to-use-an-orm

반응형