ORM支持不可变类

哪个ORM支持不可变类型的域模型?

我想编写类似下面的类(或Scala等价物):

class A { private final C c; //not mutable A(B b) { //init c } A doSomething(B b) { // build a new A } } 

ORM必须使用构造函数初始化对象 。 因此可以在构造函数中检查不变量。 默认构造函数和字段/ setter访问intialize是不够的,并使类的实现变得复杂。

应支持使用集合 。 如果更改了集合,则应从用户角度创建副本。 (渲染旧的集合状态陈旧。但用户代码仍然可以工作(或至少读取)。)就像持久数据结构一样 。

关于动机的一些话。 假设您有一个FP风格的域对象模型。 现在,您希望将其保留到数据库中。 你是谁做的? 你想在纯粹的function风格中尽可能多地做,直到邪恶的一面效果进入。如果你的域对象模型不是不可变的,你可以例如不在线程之间共享对象。 您必须复制,缓存或使用锁。 因此,除非您的ORM支持不可变类型,否则您在选择解决方案时会受到限制。

更新:我创建了一个专注于解决这个问题的项目,名为JIRM : https : //github.com/agentgt/jirm

我在使用Spring JDBC和Jackson Object Mapper实现自己之后才发现了这个问题。 基本上我只需要一些最小的SQL < - >不可变对象映射。

简而言之,我只使用Springs RowMapperJackson的ObjectMapper来从数据库中来回映射对象。 我只是为元数据使用JPA注释(比如列名等)。 如果人们有兴趣我会清理它并把它放在github上 (现在它只在我的创业公司的私人仓库中)。

这里有一个粗略的想法,它是如何工作的是一个示例bean( 注意所有字段是最终的 ):

 //skip imports for brevity public class TestBean { @Id private final String stringProp; private final long longProp; @Column(name="timets") private final Calendar timeTS; @JsonCreator public TestBean( @JsonProperty("stringProp") String stringProp, @JsonProperty("longProp") long longProp, @JsonProperty("timeTS") Calendar timeTS ) { super(); this.stringProp = stringProp; this.longProp = longProp; this.timeTS = timeTS; } public String getStringProp() { return stringProp; } public long getLongProp() { return longProp; } public Calendar getTimeTS() { return timeTS; } } 

这里是RowMapper的样子(注意它主要委托给Springs ColumnMapRowMapper,然后使用Jackson的objectmapper):

 public class SqlObjectRowMapper implements RowMapper { private final SqlObjectDefinition definition; private final ColumnMapRowMapper mapRowMapper; private final ObjectMapper objectMapper; public SqlObjectRowMapper(SqlObjectDefinition definition, ObjectMapper objectMapper) { super(); this.definition = definition; this.mapRowMapper = new SqlObjectMapRowMapper(definition); this.objectMapper = objectMapper; } public SqlObjectRowMapper(Class k) { this(SqlObjectDefinition.fromClass(k), new ObjectMapper()); } @Override public T mapRow(ResultSet rs, int rowNum) throws SQLException { Map m = mapRowMapper.mapRow(rs, rowNum); return objectMapper.convertValue(m, definition.getObjectType()); } } 

现在我只使用Spring JDBCTemplate并给它一个流畅的包装器。 这里有些例子:

 @Before public void setUp() throws Exception { dao = new SqlObjectDao(new JdbcTemplate(ds), TestBean.class); } @Test public void testAll() throws Exception { TestBean t = new TestBean(IdUtils.generateRandomUUIDString(), 2L, Calendar.getInstance()); dao.insert(t); List list = dao.queryForListByFilter("stringProp", "hello"); List otherList = dao.select().where("stringProp", "hello").forList(); assertEquals(list, otherList); long count = dao.select().forCount(); assertTrue(count > 0); TestBean newT = new TestBean(t.getStringProp(), 50, Calendar.getInstance()); dao.update(newT); TestBean reloaded = dao.reload(newT); assertTrue(reloaded != newT); assertTrue(reloaded.getStringProp().equals(newT.getStringProp())); assertNotNull(list); } @Test public void testAdding() throws Exception { //This will do a UPDATE test_bean SET longProp = longProp + 100 int i = dao.update().add("longProp", 100).update(); assertTrue(i > 0); } @Test public void testRowMapper() throws Exception { List craps = dao.query("select string_prop as name from test_bean limit ?", Crap.class, 2); System.out.println(craps.get(0).getName()); craps = dao.query("select string_prop as name from test_bean limit ?") .with(2) .forList(Crap.class); Crap c = dao.query("select string_prop as name from test_bean limit ?") .with(1) .forObject(Crap.class); Optional absent = dao.query("select string_prop as name from test_bean where string_prop = ? limit ?") .with("never") .with(1) .forOptional(Crap.class); assertTrue(! absent.isPresent()); } public static class Crap { private final String name; @JsonCreator public Crap(@JsonProperty ("name") String name) { super(); this.name = name; } public String getName() { return name; } } 

请注意,在上面将任何查询映射到不可变POJO是多么容易。 那就是你不需要1到1的实体到表。 还要注意使用Guava的选项 (最后查询..向下滚动)。 我真的很讨厌ORM如何抛出exception或返回null

如果你喜欢我,请告诉我,我会花时间把它放在github上(只有带postgresql的teste)。 否则,使用上面的信息,您可以使用Spring JDBC轻松实现自己的。 我开始真正挖掘它,因为不可变对象更容易理解和思考。

Hibernate有@Immutable注释。

这是一个指南 。

虽然不是真正的 ORM,但MyBatis可以做到这一点。 我没试过。

http://mybatis.org/java.html

AFAIK,没有完全按照您的意愿支持此function的.NET的ORM。 但是你可以看看BLTookit和LINQ to SQL – 它们都提供了逐个比较的语义,并且总是在物化上返回新的对象。 这几乎是你所需要的,但我不确定那里的藏品。

顺便问一下,为什么你需要这个function? 我知道纯函数式语言和纯粹可模拟对象的好处(例如完整的线程安全性)。 但是在使用ORM的情况下,使用这些对象执行的所有操作最终都会转换为一系列SQL命令。 所以我承认使用这些物体的好处在这里是蒸汽的。

您可以使用Ebean和OpenJPA(我认为您可以使用Hibernate但不确定)。 ORM(Ebean / OpenJPA)将生成一个默认构造函数(假设bean没有),并实际设置’final’字段的值。 这听起来有点奇怪,但最后的字段并不总是严格地说是最终的。

SORM是一个新的Scala ORM,可以完全满足您的需求。 下面的代码将比任何单词更好地解释它:

 // Declare a model: case class Artist ( name : String, genres : Set[Genre] ) case class Genre ( name : String ) // Initialize SORM, automatically generating schema: import sorm._ object Db extends Instance ( entities = Set() + Entity[Artist]() + Entity[Genre](), url = "jdbc:h2:mem:test" ) // Store values in the db: val metal = Db.save( Genre("Metal") ) val rock = Db.save( Genre("Rock") ) Db.save( Artist("Metallica", Set() + metal + rock) ) Db.save( Artist("Dire Straits", Set() + rock) ) // Retrieve values from the db: val metallica = Db.query[Artist].whereEqual("name", "Metallica").fetchOne() // Option[Artist] val rockArtists = Db.query[Artist].whereEqual("genres.name", "Rock").fetch() // Stream[Artist]