detached entity passed to persist error while using @ManyToOne association
<p>I have <code>Book</code> &amp; <code>Bookdetail</code> class</p>

<p>When I am trying to use same <code>BookDetail</code> information for my two <code>Book</code> objects using <code>@ManyToOne</code>, I am getting </p>

<blockquote>
  <p>"detached entity passed to persist error".</p>
</blockquote>

<p>I tried same with <code>JpaRepository</code> and <code>CrudRepository</code>. But same result</p>

<p>Please help me. Thanks in advance</p>

<p><strong>Main Class</strong></p>

<pre><code>@SpringBootApplication
public class HelloJpaApplication implements CommandLineRunner{

    private static final Logger logger = LoggerFactory.getLogger(HelloJpaApplication.class);

    @Autowired
    private BookRepository bookRepository;

    public void run(String... arg0) throws Exception {

        Book book1=new Book();
        book1.setName("my thoughts");

        Book book2=new Book();
        book2.setName("your thoughts");

        Bookdetail detail=new Bookdetail();
        detail.setCategory("good books");

        book1.setBookdetail(detail);
        book2.setBookdetail(detail);

        bookRepository.save(book1); 
        bookRepository.save(book2); 
    }

    public static void main(String[] args) {
        SpringApplication.run(HelloJpaApplication.class, args);
    }
}
</code></pre>

<p><strong>BookRepository interface</strong></p>

<pre><code>public interface BookRepository extends JpaRepository&lt;Book,Integer&gt;{

}
</code></pre>

<p><strong>Book class</strong></p>

<pre><code>@Entity
public class Book {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int bookid;

    private String name;

    @ManyToOne(cascade = {CascadeType.PERSIST,CascadeType.MERGE})
    private Bookdetail bookdetail;

    public Book() {
    }

    public Book(String name) {
    this.name=name;
    }

    public int getBookid() {
        return bookid;
    }
    public void setBookid(int bookid) {
        this.bookid = bookid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Bookdetail getBookdetail() {
        return bookdetail;
    }
    public void setBookdetail(Bookdetail bookdetail) {
        this.bookdetail = bookdetail;
    }

}
</code></pre>

<p><strong>Bookdetail Class</strong></p>

<pre><code>@Entity
@Table(name="bookdetail")
public class Bookdetail {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int bookid;

    private String category;

    public Bookdetail() {
    }
    public Bookdetail(String category) {
        this.category=category;
    }

    public String getCategory() {
        return category;
    }
    public void setCategory(String category) {
        this.category = category;
    }

}
</code></pre>