将JPA Hibernate与OptaPlanner集成
我們一直在改進(jìn)OptaPlanner與JEE其余部分的集成,因此,構(gòu)建可以正常工作的最終用戶應(yīng)用程序更加容易。 讓我們看一下改進(jìn)的JPA Hibernate集成。
基礎(chǔ)
JPA Hibernate和OptaPlanner都可以在POJO(普通的舊Java對(duì)象)上工作,因此只需在域?qū)ο笊咸砑右恍㎎PA批注以使其與JPA Hibernate保持一致,并添加一些OptaPlanner批注即可解決OptaPlanner的優(yōu)化問題。
在每個(gè)問題事實(shí)類上,通常只有JPA批注:
@Entity // JPA annotation public class Computer {private int cpuPower;private int memory;private int networkBandwidth;private int cost;... }在每個(gè)計(jì)劃實(shí)體類上,都有JPA和OptaPlanner批注:
@PlanningEntity // OptaPlanner annotation @Entity // JPA annotation public class Process {private int requiredCpuPower;private int requiredMemory;private int requiredNetworkBandwidth;@PlanningVariable(...) // OptaPlanner annotation@ManyToOne() // JPA annotationprivate Computer computer;... }不要將JPA實(shí)體(任何持久存儲(chǔ)在數(shù)據(jù)庫(kù)中的對(duì)象)與OptaPlanner規(guī)劃實(shí)體(在解決過程中由OptaPlanner更改的對(duì)象)混淆。
堅(jiān)持得分
默認(rèn)情況下,JPA Hibernate將通過Java序列化將Score放在BLOB列中。 這是不希望的,因?yàn)樗柚沽嗽贘PA-QL查詢中使用分?jǐn)?shù)。 此外,在升級(jí)OptaPlanner版本時(shí),它還會(huì)觸發(fā)數(shù)據(jù)庫(kù)問題。
因此,OptaPlanner 6.4.0.Beta1具有一個(gè)新的jar optaplanner-persistence-jpa ,其中包含每種評(píng)分類型的Hibernate類型。 像這樣使用它:
@PlanningSolution // OptaPlanner annotation @Entity // JPA annotation @TypeDef(defaultForType = HardSoftScore.class, typeClass = HardSoftScoreHibernateType.class) // Hibernate annotation public class CloudBalance implements Solution<HardSoftScore> {@Columns(columns = {@Column(name = "hardScore"), @Column(name = "softScore")}) // JPA annotationprivate HardSoftScore score;... }這會(huì)將HardSoftScore放入2個(gè)INTEGER列,而不是BLOB列。 OptaPlanner參考手冊(cè)包含有關(guān)如何正確處理BigDecimal和/或可彎曲分?jǐn)?shù)的更多信息。
克隆陷阱
在JPA模型中,問題事實(shí)通常引用計(jì)劃解決方案,這可能會(huì)破壞計(jì)劃克隆(如果使用默認(rèn)計(jì)劃克隆器)。
為了克服這個(gè)問題,只需使用@DeepPlanningClone注釋注釋引用計(jì)劃解決方案或計(jì)劃實(shí)體的問題事實(shí)類:
@DeepPlanningClone // OptaPlanner annotation: Force the default planning cloner to planning clone this class too @Entity // JPA annotation public class Computer {@ManyToOneprivate CloudBalance cloudBalance;... }這樣, Computer類也正在計(jì)劃克隆,并且克隆的cloudBalance字段將指向CloudBalance克隆。
結(jié)論
您可以對(duì)JPA Hibernate和OptaPlanner使用相同的域類,無需重復(fù)您的域!
翻譯自: https://www.javacodegeeks.com/2015/09/integrating-jpa-hibernate-with-optaplanner.html
總結(jié)
以上是生活随笔為你收集整理的将JPA Hibernate与OptaPlanner集成的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 现货白银怎么开户?
- 下一篇: 编写基于事件的CQRS读取模型