Ported to Hibernate 5.2.2, rewrote database query methods to not use deprecated methods.

This commit is contained in:
neviyn 2016-08-20 02:24:46 +01:00
parent 1902d11d78
commit b23e5b1ec5
6 changed files with 82 additions and 32 deletions

View File

@ -70,9 +70,14 @@
<dependency> <dependency>
<groupId>org.hibernate</groupId> <groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId> <artifactId>hibernate-core</artifactId>
<version>5.1.1.Final</version> <version>5.2.2.Final</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.2.Final</version>
</dependency>
<dependency> <dependency>
<groupId>org.hsqldb</groupId> <groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId> <artifactId>hsqldb</artifactId>

View File

@ -6,8 +6,11 @@ import org.hibernate.Criteria;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -42,6 +45,11 @@ public class HibernateDatabase implements IDatabase{
properties.put("hibernate.connection.driver_class", "org.hsqldb.jdbc.JDBCDriver"); properties.put("hibernate.connection.driver_class", "org.hsqldb.jdbc.JDBCDriver");
properties.put("hibernate.enable_lazy_load_no_trans", "true"); properties.put("hibernate.enable_lazy_load_no_trans", "true");
properties.put("hibernate.c3p0.min_size", 5);
properties.put("hibernate.c3p0.max_size", 20);
properties.put("hibernate.c3p0.timeout", 300);
properties.put("hibernate.c3p0.max_statements", 50);
if(testMode){ if(testMode){
properties.put("hibernate.connection.url", "jdbc:hsqldb:mem:."); properties.put("hibernate.connection.url", "jdbc:hsqldb:mem:.");
properties.put("hibernate.hbm2ddl.auto", "create-drop"); properties.put("hibernate.hbm2ddl.auto", "create-drop");
@ -53,7 +61,6 @@ public class HibernateDatabase implements IDatabase{
} }
sessionFactory = new Configuration() sessionFactory = new Configuration()
.addProperties(properties) .addProperties(properties)
.addPackage("musicplayer.model")
.addAnnotatedClass(Album.class) .addAnnotatedClass(Album.class)
.addAnnotatedClass(Artist.class) .addAnnotatedClass(Artist.class)
.addAnnotatedClass(Song.class) .addAnnotatedClass(Song.class)
@ -75,8 +82,17 @@ public class HibernateDatabase implements IDatabase{
*/ */
public Optional<Album> getOneAlbum(String name) { public Optional<Album> getOneAlbum(String name) {
try (Session session = getSession()) { try (Session session = getSession()) {
Criteria criteria = session.createCriteria(Album.class); CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
Album album = (Album) criteria.add(Restrictions.eq("name", name)).uniqueResult(); CriteriaQuery<Album> criteriaQuery = criteriaBuilder.createQuery(Album.class);
Root<Album> root = criteriaQuery.from(Album.class);
ParameterExpression<String> parameterExpression = criteriaBuilder.parameter(String.class);
criteriaQuery.select(root).where(criteriaBuilder.equal(root.get("name"), parameterExpression));
TypedQuery<Album> query = session.createQuery(criteriaQuery);
query.setParameter(parameterExpression, name);
Album album = null;
try{
album = query.getSingleResult();
}catch(NoResultException ignored){}
return (album == null) ? Optional.empty() : Optional.of(album); return (album == null) ? Optional.empty() : Optional.of(album);
} }
} }
@ -87,8 +103,17 @@ public class HibernateDatabase implements IDatabase{
*/ */
public Optional<Artist> getOneArtist(String name) { public Optional<Artist> getOneArtist(String name) {
try (Session session = getSession()) { try (Session session = getSession()) {
Criteria criteria = session.createCriteria(Artist.class); CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
Artist artist = (Artist) criteria.add(Restrictions.eq("name", name)).uniqueResult(); CriteriaQuery<Artist> criteriaQuery = criteriaBuilder.createQuery(Artist.class);
Root<Artist> root = criteriaQuery.from(Artist.class);
ParameterExpression<String> parameterExpression = criteriaBuilder.parameter(String.class);
criteriaQuery.select(root).where(criteriaBuilder.equal(root.get("name"), parameterExpression));
TypedQuery<Artist> query = session.createQuery(criteriaQuery);
query.setParameter(parameterExpression, name);
Artist artist = null;
try{
artist = query.getSingleResult();
}catch(NoResultException ignored){}
return (artist == null) ? Optional.empty() : Optional.of(artist); return (artist == null) ? Optional.empty() : Optional.of(artist);
} }
} }
@ -99,8 +124,17 @@ public class HibernateDatabase implements IDatabase{
*/ */
public Optional<Song> getOneSong(ExtractedMetadata metadata){ public Optional<Song> getOneSong(ExtractedMetadata metadata){
try (Session session = getSession()) { try (Session session = getSession()) {
Song song = (Song)session.createCriteria(Song.class) CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
.add(Restrictions.eq("songFile", metadata.getSongFile())).uniqueResult(); CriteriaQuery<Song> criteriaQuery = criteriaBuilder.createQuery(Song.class);
Root<Song> root = criteriaQuery.from(Song.class);
ParameterExpression<String> parameterExpression = criteriaBuilder.parameter(String.class);
criteriaQuery.select(root).where(criteriaBuilder.equal(root.get("songFile"), parameterExpression));
TypedQuery<Song> query = session.createQuery(criteriaQuery);
query.setParameter(parameterExpression, metadata.getSongFile());
Song song = null;
try{
song = query.getSingleResult();
}catch(NoResultException ignored){}
return (song == null) ? Optional.empty() : Optional.of(song); return (song == null) ? Optional.empty() : Optional.of(song);
} }
} }
@ -110,13 +144,11 @@ public class HibernateDatabase implements IDatabase{
* @param ids List of songs to keep. * @param ids List of songs to keep.
*/ */
public void batchDeleteNot(Long[] ids){ public void batchDeleteNot(Long[] ids){
try(Session session = getSession()) { try (Session session = getSession()) {
session.beginTransaction(); session.beginTransaction();
@SuppressWarnings("unchecked") //noinspection JpaQlInspection
List<Song> songs = (List<Song>)session.createCriteria(Song.class).add(Restrictions.not(Restrictions.in Query query = session.createQuery("delete from Song s where s.id not in :id_list");
("id", Arrays.asList(ids)))).list(); query.setParameter("id_list", Arrays.asList(ids)).executeUpdate();
if(songs != null && !songs.isEmpty())
songs.forEach(session::delete);
session.getTransaction().commit(); session.getTransaction().commit();
} }
} }
@ -127,8 +159,17 @@ public class HibernateDatabase implements IDatabase{
*/ */
private Optional<Song> getOneSong(Song target){ private Optional<Song> getOneSong(Song target){
try (Session session = getSession()) { try (Session session = getSession()) {
Song song = (Song)session.createCriteria(Song.class) CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
.add(Restrictions.eq("songFile", target.getSongFile().toString())).uniqueResult(); CriteriaQuery<Song> criteriaQuery = criteriaBuilder.createQuery(Song.class);
Root<Song> root = criteriaQuery.from(Song.class);
ParameterExpression<String> parameterExpression = criteriaBuilder.parameter(String.class);
criteriaQuery.select(root).where(criteriaBuilder.equal(root.get("songFile"), parameterExpression));
TypedQuery<Song> query = session.createQuery(criteriaQuery);
query.setParameter(parameterExpression, target.getSongFile().toString());
Song song = null;
try{
song = query.getSingleResult();
}catch(NoResultException ignored){}
return (song == null) ? Optional.empty() : Optional.of(song); return (song == null) ? Optional.empty() : Optional.of(song);
} }
} }
@ -139,10 +180,14 @@ public class HibernateDatabase implements IDatabase{
* @return List of all items in the database of class typeClass. * @return List of all items in the database of class typeClass.
*/ */
public <T extends IDBType> Optional<List<T>> listAllT(Class<T> typeClass){ public <T extends IDBType> Optional<List<T>> listAllT(Class<T> typeClass){
try (Session session = getSession()) { try (Session session = getSession()) {
@SuppressWarnings("unchecked") TypedQuery<T> query = session.createQuery("select x from " + typeClass.getSimpleName() + " x", typeClass);
List<T> output = session.createCriteria(typeClass).list(); List<T> result = null;
return (output == null || output.isEmpty()) ? Optional.empty() : Optional.of(output); try{
result = query.getResultList();
}catch(NoResultException ignored){}
return (result == null || result.isEmpty()) ? Optional.empty() : Optional.of(result);
} }
} }

View File

@ -25,6 +25,8 @@ import java.nio.file.Path;
import java.util.*; import java.util.*;
import java.util.List; import java.util.List;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -39,7 +41,7 @@ public class JTreeLibrary extends JPanel implements ILibrary, LibraryCallbackInt
final JTree libraryTree = new JTree(); final JTree libraryTree = new JTree();
private final Map<String, Runnable> libraryDisplayVariants = createDisplayVariantMap(); private final Map<String, Runnable> libraryDisplayVariants = createDisplayVariantMap();
private final static Map<Long, ImageIcon> albumArt = new ConcurrentHashMap<>(); private final static Map<Long, ImageIcon> albumArt = new ConcurrentHashMap<>();
private Thread albumArtCollector; private ExecutorService albumArtCollectorPool = Executors.newFixedThreadPool(2);
/** /**
* @return Map of display types for the library paired code to populate the library with data in the correct format. * @return Map of display types for the library paired code to populate the library with data in the correct format.
@ -82,10 +84,7 @@ public class JTreeLibrary extends JPanel implements ILibrary, LibraryCallbackInt
otherContainer.add(librarySearchField); otherContainer.add(librarySearchField);
this.add(otherContainer, BorderLayout.NORTH); this.add(otherContainer, BorderLayout.NORTH);
Optional<List<Album>> dbQuery = database.listAllT(Album.class); Optional<List<Album>> dbQuery = database.listAllT(Album.class);
dbQuery.ifPresent(x -> x.forEach(y -> { dbQuery.ifPresent(x -> x.forEach(y -> albumArtCollectorPool.submit(new Thread(() -> y.getAlbumArt().ifPresent(art -> albumArt.put(y.getId(), art))))));
albumArtCollector = new Thread(() -> y.getAlbumArt().ifPresent(art -> albumArt.put(y.getId(), art)));
albumArtCollector.start();
}));
} }
/** /**
@ -216,13 +215,11 @@ public class JTreeLibrary extends JPanel implements ILibrary, LibraryCallbackInt
*/ */
public void libraryUpdated() { public void libraryUpdated() {
libraryUpdating.set(false); libraryUpdating.set(false);
albumArtCollector.interrupt(); albumArtCollectorPool.shutdownNow();
albumArtCollector = new Thread(() -> { albumArtCollectorPool = Executors.newFixedThreadPool(2);
Optional<List<Album>> dbQuery = database.listAllT(Album.class); Optional<List<Album>> dbQuery = database.listAllT(Album.class);
dbQuery.ifPresent(x -> x.forEach(y -> y.getAlbumArt().ifPresent(art -> albumArt.put(y.getId(), dbQuery.ifPresent(x -> x.forEach(y -> albumArtCollectorPool.submit(new Thread(() -> y.getAlbumArt().ifPresent
art)))); (art -> albumArt.put(y.getId(),art))))));
});
albumArtCollector.start();
refreshLibrary(); refreshLibrary();
} }

View File

@ -21,6 +21,7 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
@Entity @Entity
@Table(name = "Album")
public class Album implements Comparable<Album>, IDBType, HasSongs { public class Album implements Comparable<Album>, IDBType, HasSongs {
@Id @Id

View File

@ -4,6 +4,7 @@ import javax.persistence.*;
import java.util.Set; import java.util.Set;
@Entity @Entity
@Table(name = "Artist")
public class Artist implements Comparable<Artist>, IDBType, HasSongs { public class Artist implements Comparable<Artist>, IDBType, HasSongs {
@Id @Id

View File

@ -4,6 +4,7 @@ import javax.persistence.*;
import java.io.File; import java.io.File;
@Entity @Entity
@Table(name = "Song")
public class Song implements Comparable<Song>, IDBType { public class Song implements Comparable<Song>, IDBType {
@Id @Id