title: Spring data hibernate exception: identifier of instance was altered
body: <p>I have spring boot application which use spring data and hibernate to fetch and insert data to database. 
  I have one-to-many table relation: </p>
  
  <pre><code>@Entity
  @Data
  @EqualsAndHashCode(of = { "id" })
  @Table(name = "direction")
  public class Direction {
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id", nullable = false)
  private Long id;
  
  @Column(name = "name")
  private String name;
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>@Entity
  @Table(name = "subdivision")
  @Data
  @EqualsAndHashCode()
  public class Subdivision {
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id", nullable = false)
  private Long id;
  
  @Column(name = "name")
  private String name;
  
  @ManyToOne()
  @JoinColumn(name = "direction_id", referencedColumnName = "id")
  private Direction direction;
  }
  </code></pre>
  
  <p>I have lombok plugin for boilarplate code generation.
  I also have repository</p>
  
  <pre><code>public interface SubdivisionRepository extends CrudRepository&lt;Subdivision, Long&gt; {
  
  List&lt;Subdivision&gt; findAll();
  
  List&lt;Subdivision&gt; findByDirection(Direction direction);
  
  }
  </code></pre>
  
  <p>and service</p>
  
  <pre><code>@Service
  public class SubdivisionServiceImpl implements SubdivisionService {
  
  @Autowired
  private SubdivisionRepository subdivisionRepository;
  
  @Override
  public List&lt;Subdivision&gt; findAll() {
      return subdivisionRepository.findAll();
  }
  
  @Override
  public Subdivision findById(Long id) {
      return subdivisionRepository.findById(id).get();
  }
  
  @Override
  @Transactional
  public void save(Subdivision subdivision) {
      subdivisionRepository.save(subdivision);
  }
  
  @Override
  public List&lt;Subdivision&gt; findByDirection(Direction direction) {
      return subdivisionRepository.findByDirection(direction);
  }
  }
  </code></pre>
  
  <p>That's all. Then I try to update subdirection by changing direction type it shows hibernate exception: Error during managed flush [org.hibernate.HibernateException: identifier of an instance of com.entity.Direction was altered from 2 to 3]</p>
  
  <p>I found the same question on stackoverflow but nothing suggested helped. 
  I tried to change fetch type and cascade type but it didn't helped. </p>
  
  <p>Does anyone have solution?</p>
  
  <p>P.S Here the code how I update entity</p>
  
  <pre><code>public void updateSubdivision(Subdivision subdivision){
      Direction d = directionService.findById(subdivision.getDirection().getId());
      Subdivision s = new Subdivision();
      s.setDirection(d);
      s.setName(subdivision.getName());
      s.setId(subdivision.getId());
      subdivisionService.save(s);
  }
  </code></pre>
  
  <p>It's controller method</p>