在groovy中如何使用Hibernate

标签: Hibernate

[1].[代码] groovy代码 跳至 [1] [2]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package demo
 
import javax.persistence.*
import org.hibernate.cfg.*
 
// javax.transaction jta.jar added manually to ivy repo
@Grapes([
     @Grab(group= 'org.hibernate' , module= 'hibernate-annotations' , version= '3.4.0.GA' ),
     @Grab(group= 'org.slf4j' , module= 'slf4j-simple' , version= '1.4.2' ),
     @Grab(group= 'hsqldb' , module= 'hsqldb' , version= '1.8.0.7' ),
     @Grab(group= 'javassist' , module= 'javassist' , version= '3.4.GA' ),
])
@Entity class Book {
     @Id @GeneratedValue(strategy = GenerationType.AUTO)
     public Long id
     public String author
     public String title
     String toString() { "$title by $author" }
}
 
def hibProps = [
     "hibernate.dialect" : "org.hibernate.dialect.HSQLDialect" ,
     "hibernate.connection.driver_class" : "org.hsqldb.jdbcDriver" ,
     "hibernate.connection.url" : "jdbc:hsqldb:mem:demodb" ,
     "hibernate.connection.username" : "sa" ,
     "hibernate.connection.password" : "" ,
     "hibernate.connection.pool_size" : "1" ,
     "hibernate.connection.autocommit" : "true" ,
     "hibernate.cache.provider_class" : "org.hibernate.cache.NoCacheProvider" ,
     "hibernate.hbm2ddl.auto" : "create-drop" ,
     "hibernate.show_sql" : "true" ,
     "hibernate.transaction.factory_class" : "org.hibernate.transaction.JDBCTransactionFactory" ,
     "hibernate.current_session_context_class" : "thread"
]
 
def configureHibernate(props) {
     def config = new AnnotationConfiguration()
     props. each { k, v -> config.setProperty(k, v) }
     config.addAnnotatedClass(Book)
     return config
}
 
def factory = configureHibernate(hibProps).buildSessionFactory()
 
// store some books
def session = factory.currentSession
def tx = session.beginTransaction()
session.save( new Book(author: 'Dierk et al' , title: 'Groovy in Action' ))
session.save( new Book(author: 'Craig' , title: 'Spring in Action' ))
tx.commit()
 
// find some books
session = factory.currentSession
tx = session.beginTransaction()
def books = session.createQuery( "from Book" ).list()
println 'Found ' + books. size () + ' books:'
books. each { println it }
tx.commit()

[2].[代码] groovy代码 跳至 [1] [2]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Entity class Book {
     @Id @GeneratedValue(strategy = GenerationType.AUTO)
     public Long id
     @OneToOne
     public Author author
     public String title
     String toString() { "$title by $author.name" }
}
 
@Entity class Author {
     @Id @GeneratedValue(strategy = GenerationType.AUTO)
     public Long id
     public String name
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值