1

I'm trying to get the affected rows on insert. I've seen some solution on how to do it but I don't know how to apply it on my code. I'm using spring boot and I haven't mastered it yet. This is my sample code:

Model:

@Entity
@Table(name="test_table")
public class TestTable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "name")
    private String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Repository:

public interface TestTableRepository extends CrudRepository<TestTable, Long> {

}

Service:

public interface TestTableService {
    public void saveOrUpdate(TestTable testTable);
}

Service Impl:

@Override
public void saveOrUpdate(TestTable testTable) {
    testTableRepository.save(testTable);
}

There are some unique rows so I need to know if it inserted or not.

Hoping you could help me. Thank you

trumanblack1025
  • 471
  • 2
  • 8
  • 19
  • Can you please include the `TestTable`? – Nikhil Jan 03 '19 at 02:50
  • @Nikhil Already added it! – trumanblack1025 Jan 03 '19 at 03:04
  • 1
    Assume your table in DB has set the unique constraint on the column whose value is supposed to be unique. If it executes without error ,then 1 record is inserted. If there is exception thrown , then 0 records are inserted. – Ken Chan Jan 03 '19 at 03:10
  • As Ken said, when you `save` (updates are also done with `save`) you are sending an `Entity` with the corresponding `id` (aka Primary key). So, that particular record/row will be affected. The `save` method returns the Entity, if you need to see what it has returned. [See docs](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html#save-S-) – Nikhil Jan 03 '19 at 08:17

0 Answers0