Domanda

I am getting a duplicate key exception when I tried to use a ManyToOne relationship in hiberate. I believe that I can post images here.

entity diagram

These are my classes.

  1. The Album Class album class

  2. The Song Class Song class

I am getting the below exception, when i tried to execute the unit test.

    Caused by:    com.mysql.jdbc.exceptions.jdbc4
    .MySQLIntegrityConstraintViolationException: 
    Duplicate entry 'album1' for key 'TITLE'

My Unit test class is below.

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"file:src/test/ApplicationContext-unitFav.xml"})
    public class MusicDaoImplTest{

        @Autowired
        private MusicDao musicDao;

        @Test
        public void testAddSong() {
            Album album = new Album("album1","movie",2009);
            Singer singer = new Singer("singer 1",new Date());
            Song song = new Song("song 1",album,singer,0);
            musicDao.addSong(song);
        }
    }

What time doing wrong here? when I use ManyToOne annotation, The class where i define the ManyToOne Annotation becomes the many side and the other class becomes the One side. Please note I am getting this exception , when I run the unit test for the second time.

Thanks, Arun

È stato utile?

Soluzione

The test creates a song, a signer and an album in database. And you have a unique constraint in database for the column TITLE of the album table. So, the second time you run your test, since the previous run has already created an album with the same title, you get an exception.

Make sure to always start from an empty database, or to make your tests transactional with an automatic rollback at the end.

See the documentation for explanations.

Shameless plug: to always start your tests with a database containing a well-known data set, you might consider using DbSetup.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top