@Test public void test_jsonWithPersistenceContext() { ResetBasicData.reset(); List<Order> orders = Ebean.find(Order.class) .fetch("customer", "id, name") .where() .eq("customer.id", 1) .findList(); String json = Ebean.json().toJson(orders); List<Order> orders1 = Ebean.json().toList(Order.class, json); Customer customer = null; for (Order order : orders1) { Customer tempCustomer = order.getCustomer(); if (customer == null) { customer = tempCustomer; } else { assertThat(tempCustomer).isSameAs(customer); } } }
public void testForUpdate() { ResetBasicData.reset(); Query<Order> query = Ebean.find(Order.class) .setAutofetch(false) .setForUpdate(false) .setMaxRows(1) .order() .asc("orderDate") .order() .desc("id"); int rc = query.findList().size(); Assert.assertTrue(rc > 0); Assert.assertTrue(!query.getGeneratedSql().toLowerCase().contains("for update")); query = Ebean.find(Order.class) .setAutofetch(false) .setForUpdate(true) .setMaxRows(1) .order() .asc("orderDate") .order() .desc("id"); rc = query.findList().size(); Assert.assertTrue(rc > 0); Assert.assertTrue(query.getGeneratedSql().toLowerCase().contains("for update")); }
/** * Mark the specified action as completed * * @param transactionId the unique transaction id for this action * @param scheduledActionUuid the unique name of an action */ private void markAsCompleted(String transactionId, String scheduledActionUuid) { try { Ebean.beginTransaction(); SchedulerState schedulerState = SchedulerState.getRunningSchedulerStateFromTransactionId(transactionId); if (schedulerState == null) { log.error( String.format( "Strange ... No running scheduled action for %s with transaction id %s while one was running and mark as completed is requested", scheduledActionUuid, transactionId)); } else { schedulerState.isRunning = false; schedulerState.save(); if (log.isDebugEnabled()) { log.debug( String.format( "Scheduled action for %s with transaction id %s completed", scheduledActionUuid, transactionId)); } } Ebean.commitTransaction(); } catch (Exception e) { log.error("Failed to mark as complete", e); rollbackTransactionSilent(); } finally { endTransactionSilent(); } }
@Test public void RawSqlParentLoad() { List<Data> exampleData = new ArrayList<>(); exampleData.add(new Data(0)); exampleData.add(new Data(1)); exampleData.add(new Data(2)); ChildA a = new ChildA(0); a.setData(exampleData); Ebean.save(a); ChildB b = new ChildB(1); b.setData(exampleData); Ebean.save(b); ChildA c = new ChildA(2); c.setData(exampleData); Ebean.save(c); RawSql rawSql = RawSqlBuilder.parse("select type, id, number from parent where number > 1").create(); List<Parent> partial = Ebean.find(Parent.class).setRawSql(rawSql).findList(); assertNotNull(partial.get(0).getData()); assertEquals(partial.get(0).getData().get(0).getNumber().intValue(), 0); }
public void testNoIdQuery() { Update<NoIdEntity> upd = Ebean.createUpdate(NoIdEntity.class, "delete from NoIdEntity"); upd.execute(); NoIdEntity e0 = new NoIdEntity(); e0.setId(1); e0.setValue("one"); NoIdEntity e1 = new NoIdEntity(); e1.setId(2); e1.setValue("two"); Ebean.save(e0); Ebean.save(e1); List<NoIdEntity> list = Ebean.createNamedQuery(NoIdEntity.class, "noid").findList(); Assert.assertEquals(2, list.size()); NoIdEntity noIdEntity0 = list.get(0); Assert.assertNotNull(noIdEntity0); Assert.assertEquals(noIdEntity0.getValue(), "one"); NoIdEntity noIdEntity1 = list.get(1); Assert.assertNotNull(noIdEntity1); Assert.assertEquals(noIdEntity1.getValue(), "two"); }
public void test() { TSMaster m0 = new TSMaster(); m0.setName("m1"); m0.addDetail(new TSDetail("m1 detail 1")); m0.addDetail(new TSDetail("m1 detail 2")); Ebean.save(m0); TSMaster master = Ebean.find(TSMaster.class, m0.getId()); List<TSDetail> details = master.getDetails(); TSDetail removedDetail = details.remove(1); BeanCollection<?> bc = (BeanCollection<?>) details; Set<?> modifyRemovals = bc.getModifyRemovals(); Assert.assertNotNull(modifyRemovals); Assert.assertTrue(modifyRemovals.size() == 1); Assert.assertTrue(modifyRemovals.contains(removedDetail)); Ebean.save(master); TSMaster masterReload = Ebean.find(TSMaster.class, m0.getId()); List<TSDetail> detailsReload = masterReload.getDetails(); // the removed bean has really been removed Assert.assertTrue(detailsReload.size() == 1); TSMaster master3 = Ebean.find(TSMaster.class, m0.getId()); List<TSDetail> details3 = master3.getDetails(); details3.clear(); }
/** Function to be called before delete */ private void onPreDelete() { List<Association> associations = AssociationFinder.findAssociations(this.getClass()); for (Association assoc : associations) { // Ignore if the class has the ignore on the field if (assoc.clazz.getAnnotation(CascadeIgnore.class) == null && assoc.field.getAnnotation(CascadeIgnore.class) == null) { List<? extends Model> childModels = Ebean.createQuery(assoc.clazz) .where() .eq(assoc.field.getName() + ".id", getId()) .findList(); for (Model child : childModels) { // If it is required, delete it, otherwise set it to null if (assoc.required) { child.delete(); } else { try { assoc.field.set(child, null); Set<String> set = new HashSet<String>(); set.add(assoc.field.getName()); Ebean.update(child, set); } catch (IllegalAccessException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | // File Templates. } } } } } }
public static void update(Long idGroup, List<SqlRow> gpms) { Group group = Group.findById(idGroup); if (group == null) return; Ebean.beginTransaction(); try { deleteForGroup(idGroup); Integer i = 1; for (SqlRow man : gpms) { Profile prof = Profile.lastProfileByGpmId(man.getLong("gpm")); if (prof == null) continue; CacheClassifier cc = new CacheClassifier( group, i++, prof.gpm.idGpm, prof.name, prof.image, (prof.gender == null) ? null : prof.gender.value, (prof.relationshipStatus == null) ? null : prof.relationshipStatus.status, prof.nFollowers); if (cc.name == null || cc.name.isEmpty()) cc.name = Profile.getLastNotEmptyField(prof.gpm.id, "name"); cc.save(); } Ebean.commitTransaction(); } finally { Ebean.endTransaction(); } }
@Test public void testBasicOperations() { Account e = buildAccount(-1); // Get the default EbeanServer and save EbeanServer server = Ebean.getServer(null); server.save(e); Assert.assertNotNull(e.getId()); e.setEmail("banana"); server.update(e); // find by id Account e2 = server.find(Account.class, e.getId()); Assert.assertNotNull("we found it in the db", e2); Assert.assertTrue("different instance", e2 != e); Assert.assertEquals("updated description", "banana", e2.getEmail()); server.delete(e2); Account e3 = server.find(Account.class, e.getId()); Assert.assertNull("its been deleted", e3); Query<Card> query = Ebean.find(Card.class); }
@Transactional public void doSomething(EBasicVer v) { EbeanServer server = Ebean.getServer(null); inMethodTransaction = server.currentTransaction(); Transaction t = server.createTransaction(); SqlUpdate u = server.createSqlUpdate("update e_basicver set last_update = last_update+1 where id = ?"); u.setParameter(1, v.getId()); int count = server.execute(u, t); Assert.assertEquals(1, count); t.commit(); v.setName("some change"); try { Ebean.save(v); // never get here Assert.assertTrue(false); } catch (PersistenceException e) { throw e; } }
@Override public void deleteCarouselImage(Long id) throws NotFoundException { // We use explicit transactions, since we are going to execute more than // 1 query in the same transaction Ebean.beginTransaction(); try { // We see if the carouselImage really exists if (finder.byId(id) == null) throw new NotFoundException("La imagen no existe asi que no se puede borrar"); // We delete it finder.byId(id).delete(); // Now we need to reorder all the carouselImages for (CarouselImage ci : finder.orderBy("id").findList()) { if (ci.getId() > id) { // We insert a copy of the ci in the previous position CarouselImage ciCopy = (CarouselImage) ci._ebean_createCopy(); ciCopy.setId(ci.getId() - 1); ciCopy.save(); // Then we delete the ci ci.delete(); } } Ebean.commitTransaction(); } finally { Ebean.endTransaction(); } }
@Override public void addCarouselImage(CarouselImage carouselImage) { // We use explicit transactions, since we are going to execute more than // 1 query in the same transaction Ebean.beginTransaction(); try { // We set atomatically the caroueselImage id, in order to be the // first one carouselImage.setId((long) 1); List<CarouselImage> carouselImages = finder.orderBy().desc("id").findList(); for (CarouselImage ci : carouselImages) { // We insert a copy of the ci in the next position CarouselImage ciCopy = (CarouselImage) ci._ebean_createCopy(); ciCopy.setId(ci.getId() + 1); ciCopy.save(); // Then we delete the ci ci.delete(); } // Then we save carouselImage.save(); Ebean.commitTransaction(); } finally { Ebean.endTransaction(); } }
@Test public void testQuery() { Car car = new Car(); car.setLicenseNumber("MARIOS_CAR_LICENSE"); Ebean.save(car); VehicleDriver driver = new VehicleDriver(); driver.setName("Mario"); driver.setVehicle(car); Ebean.save(driver); Query<VehicleDriver> query = Ebean.find(VehicleDriver.class); query.where().eq("vehicle.licenseNumber", "MARIOS_CAR_LICENSE"); List<VehicleDriver> drivers = query.findList(); Assert.assertNotNull(drivers); Assert.assertEquals(1, drivers.size()); Assert.assertNotNull(drivers.get(0)); Assert.assertEquals("Mario", drivers.get(0).getName()); Assert.assertEquals("MARIOS_CAR_LICENSE", drivers.get(0).getVehicle().getLicenseNumber()); Vehicle car2 = Ebean.find(Vehicle.class, car.getId()); car2.setLicenseNumber("test"); Ebean.save(car); }
public static Result save() { Form<FastSubject> fastSubjectForm = Form.form(FastSubject.class).bindFromRequest(); FastSubject fastSubject = fastSubjectForm.get(); if (fastSubject.id == null) Ebean.save(fastSubject); else Ebean.update(fastSubject); FlashMessage.updateSuccess.send(); return redirect(routes.FastSubjects.edit(fastSubject.id)); }
@Override public void onStart(Application app) { // Check if the database is empty if (User.finder.findRowCount() == 0) { Map<String, List<Object>> all = (Map<String, List<Object>>) Yaml.load("initial-data.yml"); Ebean.save(all.get("users")); Ebean.save(all.get("projects")); Ebean.save(all.get("tasks")); } }
@Transactional public static boolean revokeAccount(String email) { if (((List) OrderTire.findByUserAndNotInInitiated(email)).size() == 0) { Ebean.delete(OrderTire.findByUser(email)); Ebean.delete(User.findByEmail(email)); return true; } else { return false; } }
public void test() { ResetBasicData.reset(); Query<Order> query = Ebean.find(Order.class) .where() .eq("status", Order.Status.NEW) .ge("id", 1) .order() .desc("id"); int rc0 = query.findRowCount(); List<Object> ids = query.findIds(); Assert.assertEquals(rc0, ids.size()); List<Order> list0 = query.findList(); Assert.assertEquals(rc0, list0.size()); int rc1 = query.findRowCount(); Assert.assertEquals(rc0, rc1); List<Object> ids1 = query.findIds(); Assert.assertEquals(rc0, ids1.size()); List<Order> list1 = query.findList(); Assert.assertEquals(rc0, list1.size()); int idGt = 5; if (ids1.size() > 0) { Object id = ids.get(0); idGt = Integer.valueOf("" + id); } // should still hit query plan cache Query<Order> query2 = Ebean.find(Order.class) .where() .eq("status", Order.Status.NEW) .ge("id", idGt) .order() .desc("id"); int rc2 = query2.findRowCount(); System.out.println("Expection Not same " + rc0 + " != " + rc2); Assert.assertNotSame(rc0, rc2); List<Object> ids2 = query2.findIds(); Assert.assertEquals(rc2, ids2.size()); List<Order> list2 = query2.findList(); Assert.assertEquals(rc2, list2.size()); }
@Test public void testConnection() { String sql = "select count(*) as count from journal"; SqlRow row = Ebean.createSqlQuery(sql).findUnique(); Integer i = row.getInteger("count"); List<Journal> journal = Ebean.find(Journal.class).findList(); assertNotNull(journal); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log("new received ack message"); // start connection if it did not DB.instance().connectToDB(); // read sessionId String sessionId = request.getParameter("sessionId"); // find user with this sessionId List<ChatUser> chatUsers = Ebean.find(ChatUser.class).where().eq("sessionId", sessionId).findList(); // define the response message String responseMessage = "{}"; // this user has a sessionId if (chatUsers.size() == 1) { // current chat user ChatUser chatUser = chatUsers.get(0); log("found user for this sessionId, chatUser: "******"messageId"); List<ChatMessage> chatMessages = Ebean.find(ChatMessage.class).where().eq("messageId", messageId).findList(); if (chatMessages.size() == 1) { ChatMessage chatMessage = chatMessages.get(0); log("received message found, chatMessage: " + chatMessage); // update the status to message's last status, this message is send, received and // acknowledged, notified and acknowledged chatMessage.setStatus(ChatMessage.SOURCE_SAID_IT_KNOWS_THIS_MESSAGE_IS_DELIVERED); Ebean.update(chatMessage); log("received message updated, chatMessage: " + chatMessage); } responseMessage = "{\"status\":\"acknowledged\", \"messageId\":\"" + messageId + "\"}"; } // send response response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print(responseMessage); out.flush(); out.close(); log("done"); }
public void runExampleUsingOrders() { LoadExampleData.load(); PathProperties pathProperties = PathProperties.parse("(id,status,orderDate,customer(id,name),details(*,product(sku)))"); Query<Order> query = Ebean.createQuery(Order.class); pathProperties.apply(query); List<Order> orders = query.where().gt("id", 1).findList(); String rawJson = Ebean.json().toJson(orders); System.out.println(rawJson); }
@Test public void testInsert() { SomePeriodBean bean = new SomePeriodBean(); bean.setPeriod(Period.of(3, 4, 5)); bean.setAnniversary(MonthDay.of(4, 29)); Ebean.save(bean); SomePeriodBean bean1 = Ebean.find(SomePeriodBean.class, bean.getId()); assertEquals(bean.getPeriod(), bean1.getPeriod()); assertEquals(bean.getAnniversary(), bean1.getAnniversary()); // insert fetch null value SomePeriodBean bean2 = new SomePeriodBean(); Ebean.save(bean2); SomePeriodBean bean3 = Ebean.find(SomePeriodBean.class, bean2.getId()); assertNull(bean3.getPeriod()); assertNull(bean3.getAnniversary()); List<SomePeriodBean> anniversaryList = Ebean.find(SomePeriodBean.class) .where() .eq("anniversary", MonthDay.of(4, 29)) .eq("period_years", 3) .eq("period_months", 4) .findList(); assertEquals(1, anniversaryList.size()); // must use year 2000 for range predicates // ... using 2001 here so not finding anything anniversaryList = Ebean.find(SomePeriodBean.class) .where() .gt("anniversary", Date.valueOf(LocalDate.of(2001, 4, 29))) .findList(); assertEquals(0, anniversaryList.size()); // can use year 2000 for range predicates // ... and can use LocalDate to bind anniversaryList = Ebean.find(SomePeriodBean.class) .where() .gt("anniversary", LocalDate.of(2000, 4, 22)) .findList(); assertEquals(1, anniversaryList.size()); Ebean.delete(bean); Ebean.delete(bean2); }
public void test() { ResetBasicData.reset(); try { File f = new File("src/test/resources/test1.csv"); FileReader reader = new FileReader(f); CsvReader<Customer> csvReader = Ebean.createCsvReader(Customer.class); csvReader.setPersistBatchSize(2); csvReader.addIgnore(); // csvReader.addProperty("id"); csvReader.addProperty("status"); csvReader.addProperty("name"); csvReader.addDateTime("anniversary", "dd-MMM-yyyy", Locale.GERMAN); csvReader.addProperty("billingAddress.line1"); csvReader.addProperty("billingAddress.city"); csvReader.addReference("billingAddress.country.code"); csvReader.process(reader); } catch (Exception e) { throw new RuntimeException(e); } }
/** Rename a folder */ public static String renameFolder(String folder, String newName) { Ebean.createSqlUpdate("update project set folder = :newName where folder = :folder") .setParameter("folder", folder) .setParameter("newName", newName) .execute(); return newName; }
public void test() { ResetBasicData.reset(); String sql = " select order_id, o.status, c.id, c.name, sum(d.order_qty*d.unit_price) as totalAmount" + " from o_order o" + " join o_customer c on c.id = o.kcustomer_id " + " join o_order_detail d on d.order_id = o.id " + " group by order_id, o.status, c.id, c.name "; RawSql rawSql = RawSqlBuilder.parse(sql) .columnMapping("order_id", "order.id") .columnMapping("o.status", "order.status") .columnMapping("c.id", "order.customer.id") .columnMapping("c.name", "order.customer.name") // .columnMapping("sum(d.order_qty*d.unit_price)", "totalAmount") .create(); List<OrderAggregate> list2 = Ebean.find(OrderAggregate.class) .setRawSql(rawSql) .fetch("order", new FetchConfig().query()) .fetch("order.details", new FetchConfig().query()) .where() .gt("order.id", 2) .having() .gt("totalAmount", 10) .filterMany("order.details") .gt("unitPrice", 2d) .findList(); output(list2); }
/** * 保存分享记录,存在分享记录 * * @param */ public static void updateTuniqueurl( final String url, final int time, final String userphoneObject) { Ebean.execute( new TxRunnable() { public void run() { Tuniqueurl uniqueurl = Tuniqueurl.findDataById(url); // 判断之前是否有用户使用记录,没有使用记录 if (uniqueurl.userphoneObject == null) { uniqueurl.url = url; uniqueurl.sharetime = time; uniqueurl.userphoneObject = userphoneObject; Set<String> options = new HashSet<String>(); options.add("url"); options.add("sharetime"); options.add("userphoneObject"); Ebean.update(uniqueurl, options); } else if (uniqueurl.userphoneObject != null) { uniqueurl.url = url; uniqueurl.sharetime = time; uniqueurl.userphoneObject = uniqueurl.userphoneObject + ',' + userphoneObject; Set<String> options = new HashSet<String>(); options.add("url"); options.add("sharetime"); options.add("userphoneObject"); Ebean.update(uniqueurl, options); } } }); }
public static void updatePass(String password, String username) { String s = "update neighbors set password= :password where username = :username"; SqlUpdate update = Ebean.createSqlUpdate(s); update.setParameter("password", password); update.setParameter("username", username); update.execute(); }
@AccessLevel(level = 2) public Result create() { Form<ActivityChoice> choiceForm = Form.form(ActivityChoice.class).bindFromRequest(); if (choiceForm.hasErrors()) { return status( ErrDefinition.E_ACTIVITY_CHOICE_FORM_HASERROR, Messages.get("activitychoice.failure")); } try { ActivityChoice choice = choiceForm.get(); choice.id = CodeGenerator.GenerateUUId(); choice.content = new ActivityContent(); choice.content.id = choice.id; Ebean.save(choice); return ok(Json.toJson(choice)); } catch (Throwable e) { return status( ErrDefinition.E_ACTIVITY_CHOICE_CREATE_FAILED, Messages.get("activitychoice.failure")); } }
@Test public void test_toObject() throws Exception { EbeanServer server = Ebean.getDefaultServer(); JsonContext json = server.json(); Customer customer = new Customer(); customer.setId(1); customer.setName("Jim"); String asJson = json.toJson(customer); Object bean = json.toObject(Customer.class, asJson); assertTrue(bean instanceof Customer); assertEquals(Integer.valueOf(1), ((Customer) bean).getId()); assertEquals("Jim", ((Customer) bean).getName()); StringReader reader = new StringReader(asJson); bean = json.toObject(Customer.class, reader); assertTrue(bean instanceof Customer); assertEquals(Integer.valueOf(1), ((Customer) bean).getId()); assertEquals("Jim", ((Customer) bean).getName()); }
public Result readAll() { try { String sql = String.format( "select id, shop_id, user_id, create_time from shake_record" + " join shop on shop.id = shop_id" + " where shop.app_id = %s", session("appId")); RawSql rawSql = RawSqlBuilder.parse(sql) .columnMapping("id", "id") .columnMapping("shop_id", "shop_id") .columnMapping("user_id", "user_id") .columnMapping("create_time", "create_time") .create(); Query<ShakeRecord> query = Ebean.find(ShakeRecord.class); query.setRawSql(rawSql); List<ShakeRecord> shakeList = query.findList(); return ok(Json.toJson(shakeList)); } catch (Throwable e) { return status(ErrDefinition.E_SHAKE_RECORD_READ_ERROR, Messages.get("shakerecord.failure")); } }
@Test public void testCreateGenerator() throws Exception { EbeanServer server = Ebean.getDefaultServer(); StringWriter writer = new StringWriter(); JsonContext json = server.json(); JsonGenerator generator = json.createGenerator(writer); Customer customer = new Customer(); customer.setId(1); customer.setName("Jim"); // we can use the generator before and after our json.toJson() call // ... confirming we are not closing the generator generator.writeStartArray(); json.toJson(customer, generator, PathProperties.parse("id,name")); generator.writeEndArray(); generator.close(); String jsonString = writer.toString(); assertTrue(jsonString, jsonString.startsWith("[")); assertTrue(jsonString, jsonString.endsWith("]")); assertTrue(jsonString, jsonString.contains("{\"id\":1,\"name\":\"Jim\"}")); }