2

I am trying persist a new 'UserTopics' object and map the newly UserTopic in the 'Topic' table corresponded to multiple userId's.

I've no idea what I am doing wrong here. Below is the code I have and the exception.

My UserTopics entity:

@Entity
@Table(name="USERS_TOPICS")
public class UserTopics {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name="TOPICUSER_ID")
    private Integer id;

    @Column(name="USER_ID")
    private Integer userId;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "TOPICS_TOPICS_ID")
    private Topics topics;

    // Getters and setters

and Topics entity:

    @Entity
    @Table(name="TOPICS")
    public class Topics {

        @Id
        @GeneratedValue(strategy= GenerationType.IDENTITY)
        @Column(name="TOPICS_ID")
        private Integer id;

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

        @OneToMany(mappedBy = "topics", cascade= {CascadeType.ALL,CascadeType.PERSIST})
        private Set<UserTopics> userTopics;

       //Getter and setters

In my service Class, I am trying to save the UserTopic like so:

 @Service("userTopicsService")
    @Transactional
    public class UserTopicsServiceImpl implements UserTopicsService {


        @Autowired
        TopicsDao topicsDao;


        @Override
        public void createTopicc(int UserIdOne, int UserIdTwo) {
        Set<UserTopics> userTopics = new HashSet<>();

        Topics topic = new Topics();
        topic.setTopicName(String.valueOf(UserIdOne+UserIdTwo));

        UserTopics userTopicOne = new UserTopics();
        userTopicOne.setUserId(UserIdOne);
        userTopics.add(userTopicOne);

        UserTopics userTopicTwo = new UserTopics();
        userTopicTwo.setUserId(UserIdTwo);
        userTopics.add(userTopicTwo);

        topic.setUserTopics(userTopics);

        topicsDao.saveTopic(topic);

    }

   //Other methods...

The exception below

    18:58:54.434 [http-apr-8080-exec-9] WARN org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1048, SQLState: 23000
18:58:54.434 [http-apr-8080-exec-9] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Column 'TOPICS_TOPICS_ID' cannot be null
18:58:54.442 [http-apr-8080-exec-9] DEBUG org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Warning
java.sql.SQLWarning: Column 'TOPICS_TOPICS_ID' cannot be null
    at com.mysql.jdbc.SQLError.convertShowWarningsToSQLWarnings(SQLError.java:779)
    at com.mysql.jdbc.SQLError.convertShowWarningsToSQLWarnings(SQLError.java:707)
user2342259
  • 345
  • 2
  • 9
  • 27

2 Answers2

0

To each UserTopic you should set the Topic object before you save:

public void createTopicc(int UserIdOne, int UserIdTwo) {
    Set<UserTopics> userTopics = new HashSet<>();

    Topics topic = new Topics();
    topic.setTopicName(String.valueOf(UserIdOne+UserIdTwo));

    UserTopics userTopicOne = new UserTopics();
    userTopicOne.setUserId(UserIdOne);
    userTopicOne.setTopics(topic);
    userTopics.add(userTopicOne);

    UserTopics userTopicTwo = new UserTopics();
    userTopicTwo.setUserId(UserIdTwo);
    userTopicTwo.setTopics(topic);
    userTopics.add(userTopicTwo);

    topic.setUserTopics(userTopics);

    topicsDao.saveTopic(topic);

Update

Additionally in your Topics entity .. use hibernate cascade option like follwoing (instead of the JPA one):

@OneToMany(mappedBy = "topics")
@Cascade({CascadeType.SAVE_UPDATE})
private Set<UserTopics> userTopics;
Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
  • I've tried, but I am getting the same error (see below). `insert into TOPIC_USERS (TOPICS_TOPICS_ID, USER_ID) values (?, ?) Hibernate: insert into TOPIC_USERS (TOPICS_TOPICS_ID, USER_ID) values (?, ?) com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'TOPICS_TOPICS_ID' cannot be null` – user2342259 Jan 22 '17 at 20:17
  • @ MaciejKowalski I was thinking to try to save the UserTopic, return the ID from the session and then call persist and pass in the collection of the new Topics where I will set the UserTopic I just created... – user2342259 Jan 22 '17 at 20:17
  • Yes, but why would you need the cascading then for? I have added one more datail that you can check. Try it out and let me know – Maciej Kowalski Jan 22 '17 at 20:24
  • So far I was using getSession().persist(topic); now I've tried with getSession().save(topic) and I've noticed that the Topic is being saved but the UserTopics still empty. Start missing the entityManager at this point...:) – user2342259 Jan 22 '17 at 21:03
  • getSession().save(topic) will save the topic only if I change the @Cascade({CascadeType.SAVE_UPDATE}) to PERSIST. With the SAVE_UPDATE it will throw the same exception Column 'TOPICS_TOPICS_ID' cannot be null – user2342259 Jan 22 '17 at 21:11
  • Ok so with PERSIST, you do not get any errors? just rows are not inserted right? – Maciej Kowalski Jan 22 '17 at 21:25
  • Exactly but in the console the hibernate generated query will look like that - insert into TOPICS (TOPICNAME, TOPICSTATUS) values (?, ?). So the insert into TOPIC_USERS (TOPICS_TOPICS_ID, USER_ID) values (?, ?) is not being generated. It saves the UserTopic but is not trying to update the Topic. I guess that's why it work – user2342259 Jan 22 '17 at 21:34
0

So the solution is:

Added cascade type to Topics object in the UserTopics entity as such:

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "TOPICS_TOPICS_ID")
    private Topics topics;

while the code in my Service class which saves the new Topic and its children UserTopics is below.

    Topics topic = new Topics();
    topic.setTopicName(String.valueOf(UserIdOne+UserIdTwo));

    Set<UserTopics> userTopics = new HashSet<>();

    UserTopics userTopicOne = new UserTopics();
    userTopicOne.setUserId(UserIdOne);
    userTopicOne.setTopics(topic);

    UserTopics userTopicTwo = new UserTopics();
    userTopicTwo.setUserId(UserIdTwo);
    userTopicOne.setTopics(topic);

    userTopics.add(userTopicOne);
    userTopics.add(userTopicTwo);

    List<UserTopics> userTopicsList = new ArrayList<>();
    userTopics.add(userTopicOne);
    userTopics.add(userTopicTwo);

    for(UserTopics next : userTopics) {
        userTopicsDao.save(next);
    }
user2342259
  • 345
  • 2
  • 9
  • 27