I am trying to learn how to use spring with JPA to connect to a database. I do not want to use persistence.xml and want to create an entity manager using the least amount of code possible.
So, I tried this solution from this page (https://vladmihalcea.com/how-to-bootstrap-jpa-programmatically-without-the-persistence-xml-configuration-file/) and it worked. However, it looks more complicated than I want it to be, and it does not incorporate any spring elements or any annotations to lessen the amount of code.
my code incorporates a solution from this question (Create JPA EntityManager without persistence.xml configuration file)
I took the configuration code from Tobogganski, he wrote it for Postgresql, and I am trying to make it work for Mysql.
The Config.java file
package jj;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
@Configuration
@EnableAutoConfiguration
@EntityScan(basePackages= "entity")
public class Config {
private final String DB_URL = "jdbc:mysql://localhost:3306/dictionary";
private final String DB_USER_NAME = "root";
private final String DB_PASSWORD = "";
@Bean
public Properties hibernateProperties(){
final Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.id.new_generator_mappings", false);
properties.put("hibernate.connection.datasource", getMysqlDataSource());
return properties;
}
@Bean
protected DataSource getMysqlDataSource() {
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setURL(DB_URL);
mysqlDataSource.setUser(DB_USER_NAME);
mysqlDataSource.setPassword(DB_PASSWORD);
return mysqlDataSource;
}
@Bean(name = "emf")
public EntityManagerFactory entityManagerFactory( DataSource dataSource, Properties hibernateProperties ){
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource( dataSource );
em.setJpaVendorAdapter( new HibernateJpaVendorAdapter() );
em.setJpaProperties( hibernateProperties );
em.setPersistenceUnitName( "dictionary" );
em.setPersistenceProviderClass(HibernatePersistenceProvider.class);
em.afterPropertiesSet();
return em.getObject();
}
}
The DictElement class
package entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PersistenceUnit;
import org.springframework.stereotype.Component;
@Component
@Entity
@PersistenceUnit(unitName="dictionary")
public class DictElement {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@Column
private String word;
@Column
private String genre;
@Column
private String definition;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
}
The driver class
package ui;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import entity.DictElement;
import jj.Config;
public class driver {
public static void main(String[] args) {
ApplicationContext ctx =new AnnotationConfigApplicationContext(Config.class);
EntityManagerFactory emf= (EntityManagerFactory) ctx.getBean("emf", EntityManagerFactory.class);
EntityManager em = null;
try {
em= emf.createEntityManager();
DictElement element= new DictElement();
element.setWord("word");
element.setGenre("type");
element.setDefinition("definition");
em.getTransaction().begin();
em.persist(element);
em.getTransaction().commit();
} catch (Exception ex)
{
ex.printStackTrace();
if (em != null)
{
em.getTransaction().rollback();
}
}
}
}
Finally, the database name is dictionary, it contains one table called "dict_table", the table is made of three columns the first is "word", the second is "genre", the the third is "definition".
When I run this code, it gives me an error 'No persistence unit with name 'dictionary' found ', but I am sure that there is more problems with my code.
the thing is, how Can I substitute this line from persistence.xml which we are not using here
( persistence-unit name="dictionary" transaction-type="RESOURCE_LOCAL" )
with only java code and annotations.
and as you can see from the driver class. I am trying to insert one element to the local database table.