Ebean使用了和JPA一样的映射,所以你可以使用@Entity, @Table, @Column, @OneToMany等等对你的实体进行注释
@Entity
public class B_Order extends CModel {
public String uuid = null;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer id;
@Constraints.Required
@Version
public Integer version = 1;
@ManyToOne
@Column(nullable = false)
public B_Customer customer;
public int status;
public String shipDate;
public String orderDate;
public int price;
}
B_Customer customer = Ebean.find(B_Customer.class, 4);
执行的sql为:
select t0.id c0, t0.uuid c1, t0.name c2, t0.version c3 from b_customer t0 where t0.id = 4
List<B_Customer> customers = Ebean.find(B_Customer.class)
.where().like("name", "%a%")
.orderBy("name desc")
.findList();
执行的sql为:
select t0.id c0, t0.uuid c1, t0.name c2, t0.version c3 from b_customer t0 where t0.name like '%a%' order by t0.name desc
你可以使用select()和fetch()查询你需要的属性。
List orderList =Ebean.find(B_Order.class).select("id").where().eq("status",B_Order.STATUS_ACTIVE).findList();
执行的sql为:
select t0.id c0 from b_order t0 where t0.status = 1
List orderList =Ebean.find(B_Order.class).select("id")
.fetch("customer","name")
.where().eq("status",B_Order.STATUS_ACTIVE)
.findList();
执行sql为:
select t0.id c0, t1.id c1, t1.name c2 from b_order t0 left outer join b_customer t1 on t1.id = t0.customer_id where t0.status = 1
String q = "find b_order fetch customer where id=:id";
B_Order order = Ebean.createQuery(B_Order.class,q).setParameter("id", 23).findUnique();
执行的sql为:
select t0.id c0, t0.uuid c1, t0.status c2, t0.ship_date c3, t0.order_date c4, t0.version c5, t1.id c6, t1.uuid c7, t1.name c8, t1.version c9 from b_order t0 left outer join b_customer t1 on t1.id = t0.customer_id where t0.id = 23
等价于:
B_Order order = Ebean.createQuery(B_Order.class).fetch("customer").where().eq("id",23).findUnique();
你可以在这种使用例如sum()、count()、max()等功能。
String sql ="select o.id ,o.customer_id, c.name , sum(price) as price from b_order o join b_customer c on o.customer_id = c.id group by customer_id";
RawSql rawSql = RawSqlBuilder.parse(sql)
.columnMapping("c.name","customer.name")
.columnMapping("o.customer_id","customer.id")
.columnMapping("o.id","id")
.create();
Query query = Ebean.find(B_Order.class);
List orderList = query.setRawSql(rawSql).findList();
注意:外键一定要查询出来,否则会报Query threw SQLException:Column Index out of range, 0 < 1.错误
Order order = Ebean.find(Order.class, 12);
order.price = 2;
Ebean.save(order);
Order order = Ebean.find(Order.class, 12);
Ebean.delete(order);
@Transactional
public void runFirst() throws IOException {
User u1 = Ebean.find(User.class, 1);
…
Customer cust = Ebean.find(Customer.class, 27);
…
Ebean.save(cust);
}
注意:函数中的异常不能使用try catch进行抓取,不然事务不起作用。play框架中必须放在最外层Result controller上,不然不起作用。
Ebean.beginTransaction();
try {
...
Ebean.save(customer);
Ebean.save(order);
Ebean.commitTransaction();
} finally {
Ebean.endTransaction();
}