forked from ebean-orm/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProductTest.java
More file actions
101 lines (74 loc) · 2.33 KB
/
Copy pathProductTest.java
File metadata and controls
101 lines (74 loc) · 2.33 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package org.example.domain;
import io.ebean.AcquireLockException;
import io.ebean.Ebean;
import io.ebean.Query;
import io.ebean.Transaction;
import org.example.domain.query.QProduct;
import org.example.service.LoadExampleData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import java.sql.SQLException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ProductTest {
private static final Logger log = LoggerFactory.getLogger(ProductTest.class);
@Test
public void findSome() {
LoadExampleData.load();
List<Product> products = new QProduct()
.name.istartsWith("c")
.id.greaterThan(0)
.sku.icontains("c")
.findList();
products.size();
}
// Run using Postgres with forUpdateNoWait
@Test(enabled = false)
public void checkLockRelease() {
LoadExampleData.load();
Transaction txn0 = Ebean.beginTransaction();
try {
Product newProd = new Product("Copper", "COP");
Ebean.save(newProd);
List<Product> list = Product.find.where()
.name.istartsWith("c")
.orderBy()
.name.asc()
.setForUpdate(true)
.findList();
Product firstProduct = list.get(0);
Query<Product> queryById =
Product.find.where()
.id.eq(firstProduct.getId())
.forUpdateNoWait()
.query();
// Ebean.findNative(Product.class, "select * from product where id = :id for update nowait")
// .setParameter("id", firstProduct.getId());
assertThat(obtainWithLock(queryById)).isFalse();
try {
txn0.getConnection().commit();
//txn0.commitAndContinue();
} catch (SQLException e) {
e.printStackTrace();
}
assertThat(obtainWithLock(queryById)).isTrue();
txn0.commit();
} finally {
txn0.end();
}
}
private boolean obtainWithLock(Query<Product> queryById) {
Transaction otherTxn1 = Ebean.getDefaultServer().createTransaction();
try {
Product other = Ebean.getDefaultServer().findOne(queryById, otherTxn1);
other.getName();
return true;
} catch (AcquireLockException e) {
log.info("Failed to obtain lock" + e.getMessage());
return false;
} finally {
otherTxn1.end();
}
}
}