Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8926473
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T07:58:47+00:00 2026-06-15T07:58:47+00:00

I have a following SQL schema layout: — postgresql82+ syntax create table AudioTracks (

  • 0

I have a following SQL schema layout:

-- postgresql82+ syntax

create table AudioTracks (
  id serial primary key 
, name text
, size integer
, filePath text
, additionDate timestamp default now()
);

create table Genres (
  id serial primary key
, name text unique -- here is the unique constraint which troubles me 
, description text
, additionDate timestamp default now()
);

create table AudioTrackGenre (
  genreId integer references Genres (id) unique 
, audioTrackId integer references AudioTracks (id) unique 
, additionDate timestamp default now()
);

And two corresponding mappings to tables:

@Entity(name = "AudioTracks")
public class AudioTrack implements Serializable {
    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column
    private String name;

    @Column
    private Integer size;

    @Column
    private String filePath;

    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private Date additionDate;


    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL )
    @JoinTable(name = "AudioTrackGenre",
            joinColumns =  { @JoinColumn(name = "audioTrackId") },
            inverseJoinColumns = { @JoinColumn(name = "genreId") }
    )
    @OrderBy("name")
    private Set<Genre> genres = new HashSet<Genre>();

    // setter/getter methods //
    ....
}

and

@Entity(name = "Genres")
public class Genre implements Serializable {
    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column
    private String name;

    @Column
    private String description;

    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private Date additionDate;

    @ManyToMany(mappedBy = "genres")
    private Set<AudioTrack> audioTracks = new HashSet<AudioTrack>();

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

    // setter/getter methods //
    ....
}

But whenever i am trying to save AudioTrack, populated with Genres which are already exists in Genres table, like here:

        Set<Genre> genres = new HashSet<Genre>();
        genres.add(new Genre("ambient"));

        AudioTrack track = new AudioTrack();
        track.setGenres(genres);

        audioTrackService.addAudioTrack(track);

(the audioTrackService.addAudioTrack(track) thing does sessionFactory.getCurrentSession().save(track) at lowest DAO level)

i am getting:

ERROR: ERROR: duplicate key value violates unique constraint "genres_name_key"
  Detail: Key (name)=(ambient) already exists.

How do i tell Hibernate not to try to re-insert already existing genres to Genres table on cascade inserts?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T07:58:48+00:00Added an answer on June 15, 2026 at 7:58 am

    If the genre already exists, you must provide its id.

    Look at this line: new Genre("ambient").

    How could hibernate possibly guess what is the existing id of the Genre ambient?

    Hibernate tries to insert the corresponding genre, because you haven’t provided its id.

    When you insert the audio track, hibernate must inserts records in the AudioTrackGenre table. Hibernate must know the ids of the genres. Otherwise hibernate assumes they are new genres.

    Edit:

    It seems you are adding genres on demand(like StackOverflow tags).

    You can do the following in your code:

    for (String genreName : submittedTextGenres) {
       Genre genre = genreDAO.findByName(genre);
       if (genre == null) { //a new genre
          genre = new Genre(genreName);
       }
    
       audioTrack.addGenre(genre);
    }
    

    If you are afraid of a concurrent user adding the same genres: (suggestion by JB Nizet)

    for (String genreName : submittedTextGenres) {
       Genre genre = genreDAO.findByName(genre);
       if (genre == null) { //a new genre
          try {
             genre = genreDAO.insertGenre(genre); //a transaction
          } catch (GenreExistsException) {
             genre = genreDAO.findByName(genre); //a separate transaction
          }
       }
    
       audioTrack.addGenre(genre);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following pseudo-SQL schema: table flight id int primary key date timestamp
I have the following table schema: create table SerialNo2( IncarnationID_UID counter primary key, Mark
I have the following SQL Server stored procedure : BEGIN TRAN CREATE TABLE #TempTable
I have the following sql table schema: procudtId productPrice Color ================================== 1 3 $
I have the following db schema. SQL> describe USERS; Name Null? Type ----------------------------------------- --------
I have test_scores table with following fields: Table schema: id (number) score1 (number) score2
I have the following database schema: table courses: id tutor_id title table course_categories: id
I have the following schema: Database: test. Table: per_login_user, Field: username (PK), password Database:
I have the following schema: TABLE bands -> band_id -> property1 -> property2 ->
I have the following database schema (Microsoft SQL Server Compact Edition): How can I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.