Spring Data JPA save()

For example, there are many students in a class.

class Group {
    int id;
    List<Student> students;
}

class Student {
    int id;
    String name;
}

I got a new one new_groupand there is one in the database old_group. Now to throw it into the database, for students, because I don't want to delete all and insert again (that's what I used to do before), so at first, I figured out a way.

for old_students
    if (old_students.contains(new_student))
        continue
    else
        old_students.add(new_student)

also overridden the equals()method

public boolean equals(Object obj) {
    if (obj instanceof Student) {
        Student s = (Student) obj;
        return s.getId() == this.id;
    }
    return super.equals(obj);
}

Then I found that it was still inappropriate, in case the student changed his name...

Let's use JPA directly, so I took a look at save()how to do it

class SimpleJpaRepository

@Transactional
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}
class AbstractEntityInformation

public boolean isNew(T entity) {

    ID id = getId(entity);
    Class<ID> idType = getIdType();

    if (!idType.isPrimitive()) {
        return id == null;
    }

    if (id instanceof Number) {
        return ((Number) id).longValue() == 0L;
    }

    throw new IllegalArgumentException(String.format("Unsupported primitive id type %s!", idType));
}

The result is also an id. Well, in the end, mergeit's okay. In fact, as long as I assemble the final one students, I don't need to worry about the rest. If it is used, the @DynamicUpdateefficiency is quite high from the perspective of SQL.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325835125&siteId=291194637