/** * 批量插入数据,可以携带ID,但没有ID的不会进行ID赋值 * * @param entityList 实体 * @return 变更条数 */ default long createWithId(@Nonnull Collection<T> entityList) { SQLInsertClause insert = sql().insert(root()); entityList.forEach(t -> { beforeCreate(t); validOnCreate(t); insert.populate(t, DefaultMapper.WITH_NULL_BINDINGS).addBatch(); }); long size = insert.getBatchCount(); if (size > 0) { insert.execute(); } insert.clear(); return size; } }
/** * 新增数据 * * @param entity 实体 * @param setId 是否设置ID * @return ID */ default long create(@Nonnull T entity, boolean setId) { beforeCreate(entity); validOnCreate(entity); Long id = entity.getId(); if (null == id) { id = sql().insert(root()) .populate(entity) .executeWithKey(pk()); } else { sql().insert(root()) .populate(entity) .execute(); } if (null == id) { throw new HuiCheException("新增数据失败"); } else { if (setId) { entity.setId(id); } return id; } }
@Test public void getSQLWithPreservedColumnOrder() { com.querydsl.sql.domain.QEmployee emp1 = new com.querydsl.sql.domain.QEmployee("emp1"); SQLInsertClause insert = new SQLInsertClause(null, SQLTemplates.DEFAULT, emp1); insert.populate(emp1); SQLBindings sql = insert.getSQL().get(0); assertEquals("The order of columns in generated sql should be predictable", "insert into EMPLOYEE (ID, FIRSTNAME, LASTNAME, SALARY, DATEFIELD, TIMEFIELD, SUPERIOR_ID)\n" + "values (EMPLOYEE.ID, EMPLOYEE.FIRSTNAME, EMPLOYEE.LASTNAME, EMPLOYEE.SALARY, EMPLOYEE.DATEFIELD, EMPLOYEE.TIMEFIELD, EMPLOYEE.SUPERIOR_ID)", sql.getSQL()); }
@Test public void populate_with_beanMapper() { Employee employee = new Employee(); employee.setFirstname("John"); insert(e).populate(employee, new BeanMapper()).execute(); }
@Test @Ignore @ExcludeIn({DERBY}) public void insert_nulls_in_batch2() { Mapper<Object> mapper = DefaultMapper.WITH_NULL_BINDINGS; // QFoo f= QFoo.foo; // SQLInsertClause sic = new SQLInsertClause(c, new H2Templates(), f); // Foo f1=new Foo(); // sic.populate(f1).addBatch(); // f1=new Foo(); // f1.setC1(1); // sic.populate(f1).addBatch(); // sic.execute(); QEmployee employee = QEmployee.employee; SQLInsertClause sic = insert(employee); Employee e = new Employee(); sic.populate(e, mapper).addBatch(); e = new Employee(); e.setFirstname("X"); sic.populate(e, mapper).addBatch(); assertEquals(0, sic.execute()); }
@Test public void insert_update_query_and_delete() { // Insert Employee employee = new Employee(); employee.setFirstname("John"); Integer id = insert(e).populate(employee).executeWithKey(e.id); assertNotNull(id); employee.setId(id); // Update employee.setLastname("S"); assertEquals(1L, update(e).populate(employee).where(e.id.eq(employee.getId())).execute()); // Query Employee smith = query().from(e).where(e.lastname.eq("S")).limit(1).select(e).fetchFirst(); assertEquals("John", smith.getFirstname()); // Delete (no changes needed) assertEquals(1L, delete(e).where(e.id.eq(employee.getId())).execute()); }
Integer id = insert(e).populate(employee).executeWithKey(e.id); employee.setId(id);