I have two entities, two controllers for that entities, clean java config for spring configuration. One controller for entity works fine, I can add data to database. Second controller, which is same just another entity wont work, I cant add data to database.
This is EmployeeDetailController class:
#Controller
#RequestMapping("/employeeDetail")
public class EmployeeDetailController {
#Autowired
private EmployeeService employeeService;
#GetMapping("/listEmployeeDetail")
public String listEmployeeDetail(Model theModel) {
// get customers from the service
List<EmployeeDetail> theEmployeeDetail = employeeService.listEmployeeDetail();
// add the customers to the model
theModel.addAttribute("employeeDetails", theEmployeeDetail);
return "list-employeeDetail";
}
#GetMapping("/showFormForAddEmployeeDetail")
public String showFormForAddEmployeeDetail(Model theModel) {
// create model attribute to bind form data
EmployeeDetail theEmployeeDetail = new EmployeeDetail();
theModel.addAttribute("employeeDetail", theEmployeeDetail);
return "addNewEmployeeDetailForm";
}
#PostMapping("/addNewEmployeeDetail")
public String addNewEmployeeDetail(#ModelAttribute("employeeDetail") EmployeeDetail theEmployeeDetail) {
// save the customer using our service
employeeService.addNewEmployeeDetail(theEmployeeDetail);
return "redirect:/employeeDetail/listEmployeeDetail";
}
}
And this is addNewEmployeeDetailForm.jsp part of code for that:
<form:form action="addNewEmployeeDetail" modelAttribute="employeeDetail" method="POST">
When I run it, app open me a form to add data, after I click save, its 404 not found.
While this is my another controller:
EmployeeController:
#Controller
#RequestMapping("/employee")
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
#GetMapping("/list")
public String listEmployee(Model theModel) {
// get customers from the service
List<Employee> theEmployee = employeeService.listEmployee();
// add the customers to the model
theModel.addAttribute("employees", theEmployee);
return "list-employee";
}
#GetMapping("/showFormForAdd")
public String showFormForAdd(Model theModel) {
// create model attribute to bind form data
Employee theEmployee = new Employee();
theModel.addAttribute("employee", theEmployee);
return "addNewEmployeeForm";
}
#PostMapping("/addNewEmployee")
public String addNewEmployee(#ModelAttribute("employee") Employee theEmployee) {
// save the customer using our service
employeeService.addNewEmployee(theEmployee);
return "redirect:/employee/list";
}
}
And addNewEmployeeForm.jsp part of code for form to add data:
<form:form action="addNewEmployee" modelAttribute="employee" method="POST">
That works fine, while first controller doesnt work.
This is my DemoAppConfig:
#Configuration
#EnableWebMvc
#ComponentScan("ets")
#EnableTransactionManagement
#PropertySource("classpath:persistence-mysql.properties")
public class DemoAppConfig implements WebMvcConfigurer {
#Autowired
private Environment env;
private Logger logger = Logger.getLogger(getClass().getName());
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public DataSource dataSource() {
// create connection pool
ComboPooledDataSource myDataSource = new ComboPooledDataSource();
// set the jdbc driver
try {
myDataSource.setDriverClass("com.mysql.jdbc.Driver");
}
catch (PropertyVetoException exc) {
throw new RuntimeException(exc);
}
// for sanity's sake, let's log url and user ... just to make sure we are reading the data
logger.info("jdbc.url=" + env.getProperty("jdbc.url"));
logger.info("jdbc.user=" + env.getProperty("jdbc.user"));
// set database connection props
myDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
myDataSource.setUser(env.getProperty("jdbc.user"));
myDataSource.setPassword(env.getProperty("jdbc.password"));
// set connection pool props
myDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize"));
myDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize"));
myDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize"));
myDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime"));
return myDataSource;
}
// need a helper method
// read environment property and convert to int
private int getIntProperty(String propName) {
String propVal = env.getProperty(propName);
// now convert to int
int intPropVal = Integer.parseInt(propVal);
return intPropVal;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(
new String[]{"ets.entity"});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager
= new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty(
"hibernate.hbm2ddl.auto", "update");
hibernateProperties.setProperty(
"hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return hibernateProperties;
}
}
EmployeeDAOImpl:
#Override
public void addNewEmployeeDetail(EmployeeDetail theEmployeeDetail) {
Session currentSession = sessionFactory.getCurrentSession();
currentSession.saveOrUpdate(theEmployeeDetail);
}
EmployeeServiceImpl:
#Override
#Transactional
public void addNewEmployeeDetail(EmployeeDetail theEmployeeDetail) {
employeeDAO.addNewEmployeeDetail(theEmployeeDetail);
}
I noticed that in my entity class EmployeeDetails constructor:
public EmployeeDetail(int workExperience, String hobby, String nationality) {
this.workExperience = workExperience;
this.hobby = hobby;
this.nationality = nationality;
}
is never used. While constructor from entity Employee is used.
SQL
use `etsystem`;
create table employee (
employee_id BIGINT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
email VARCHAR(30) NOT NULL,
PRIMARY KEY (employee_id)
);
create table employee_detail (
employee_detail_id BIGINT NOT NULL,
nationality VARCHAR(30) NOT NULL,
hobby VARCHAR(30) NOT NULL,
work_experience int(11) NOT NULL,
PRIMARY KEY (employee_detail_id),
CONSTRAINT employee_details FOREIGN KEY (employee_detail_id) REFERENCES employee (employee_id) ON DELETE NO ACTION ON UPDATE NO ACTION
);
Related
First time I encounter this problem. The situation is:
I have more than 100 SQL databases, each one correspond to a different company and each one have the same three tables (same table names, same column names, same column data type).
Is there some way to map all these databases dynamically?
With dynamically I mean to have one class to which I can refer and make any CRUD operation.
After some research I could see what I wanted to do:
Basically I needed to change my data source in run time, for that I used a spring framework interface called AbstracRoutingDataSource.
Example:
Implementing AbstractRoutingDataSource:
public class MultiRoutingDataSource extends AbstractRoutingDataSource {
#Override
protected Object determineCurrentLookupKey() {
return DBContextHolder.getCurrentDb();
}
}
DatabaseContextHolder:
public class DBContextHolder {
private static final ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal<>();
public static void setCurrentDb(DBTypeEnum dbType) {
contextHolder.set(dbType);
}
public static DBTypeEnum getCurrentDb() {
return contextHolder.get();
}
public static void clear() {
contextHolder.remove();
}
}
Database type enum:
public enum DBTypeEnum{
DATASOURCE1("DATASOURCE1"),
DATASOURCE2("DATASOURCE2");
DBTypeEnum(final String dbTypeEnum){
this.dbTypeEnum = dbTypeEnum;
}
private String dbTypeEnum;
public String dbTypeEnum(){
return dbTypeEnum;
}
}
Persistence configuration:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
basePackages = "base.packages.path",
entityManagerFactoryRef = "multiEntityManager",
transactionManagerRef = "multiTransactionManager"
)
public class PersistenceConfiguration {
private final String PACKAGE_SCAN = "base.package.path";
#Bean(name = "dataSource1")
#ConfigurationProperties("spring.datasource1")
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
#Bean(name = "dataSource2")
#ConfigurationProperties("spring.datasource2")
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
#Bean(name = "multiRoutingDataSource")
public DataSource multiRoutingDataSource() {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DBTypeEnum.DATASOURCE1, dataSource1());
targetDataSources.put(DBTypeEnum.DATASOURCE2, dataSource2());
MultiRoutingDataSource multiRoutingDataSource = new MultiRoutingDataSource();
multiRoutingDataSource.setDefaultTargetDataSource(dataSource1());
multiRoutingDataSource.setTargetDataSources(targetDataSources);
return multiRoutingDataSource;
}
#Bean(name = "multiEntityManager")
public LocalContainerEntityManagerFactoryBean multiEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(multiRoutingDataSource());
em.setPackagesToScan(PACKAGE_SCAN);
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(hibernateProperties());
return em;
}
#Bean(name = "multiTransactionManager")
public PlatformTransactionManager multiTransactionManager() {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
multiEntityManager().getObject());
return transactionManager;
}
#Bean(name = "dbSessionFactory")
public LocalSessionFactoryBean dbSessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(multiRoutingDataSource());
sessionFactoryBean.setPackagesToScan(PACKAGE_SCAN);
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.show_sql", true);
properties.put("hibernate.format_sql", true);
return properties;
}
}
Then you need to have all of your database information in a .properties file:
spring.datasource1.jdbcUrl=jdbc:sql:sql-url:3306/datasource1
spring.datasource1.username=username
spring.datasource1.password=password
spring.datasource1.driver-class-name= Driver
spring.datasource2.jdbcUrl=jdbc:sql:sql-url:3306/datasource2
spring.datasource2.username=username
spring.datasource2.password=password
spring.datasource2.driver-class-name= Driver
Then you need to map your entity:
#Entity
#Table(name = "table_name")
#Getter
#Setter
public class MyEntity implements Serializable {
#Id
#Column(name = "ID", columnDefinition = "varchar(17)")
private String id;
//more fields...
}
I used spring CrudRepositories interface for this entity
public interface IMyEntityRepository extends CrudRepository<MyEntity, String> {
}
Finally my controller is prepared to change datasource depending on a JSON field in my request.
JSON:
{
"dataSource":"DATASOURCE1"
//more fields ...
}
RESTController:
#PutMapping("/url/{id}")
public ResponseEntity<?> editMyEntity(#RequestBody RequestObject request #PathVariable String id){
DBContextHolder.setCurrentDb(DBTypeEnum.valueOf(request.getDataSource);
iMyEntitiRepository.getMyEntity(id);
//...
}
console after app runsI'm building an application that reads data from h2 database and write it into xml file. The program runs with no errors, but there is no data been written to my xml file.
I created main class
controller class: (family.java) contains setters.
Test Config class: contains all steps needed to read and write the data.
application Properties: contains the information needed to connect to database.
family Data: file i created to transfer data from h2db.
data Sql file : the sql file i use to create my table.
application.prperties
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.h2.console.path=/h2-console
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:navin
spring.datasource.data-username=sa
spring.datasource.data-password=
data.sql
DROP TABLE IF EXISTS family;
CREATE TABLE family (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(250) NOT NULL,
description VARCHAR(250) NOT NULL
);
INSERT INTO family (name, description) VALUES
('zakaria', 'I am the father'),
('Yahya', 'I am the oldest son in the house'),
('Zaid', 'I am the middle son in the house'),
('Mouad', 'I am the cutest boy in the house');
#Configuration
#EnableBatchProcessing
public class TestConfig {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Autowired
public DataSource dataSource;
#Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("dataSorce.driverClassName");
dataSource.setUrl("dataSource.url");
dataSource.setUsername("dataSource.username");
dataSource.setPassword("dataSource.password");
return dataSource;
}
public JdbcCursorItemReader<family> reader(){
JdbcCursorItemReader<family> reader = new JdbcCursorItemReader<family>();
reader.setDataSource(dataSource);
reader.setSql("SELECT id,name,description FROM family");
reader.setRowMapper(new FamilyRowMapper());
return reader;
}
public class FamilyRowMapper implements RowMapper<family> {
#Override
public family mapRow(ResultSet rs, int rowNum) throws SQLException {
family user = new family();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setDescription(rs.getString("description"));
return user;
}
}
#Bean
public StaxEventItemWriter<family> writer(){
StaxEventItemWriter<family> writer = new StaxEventItemWriter<family>();
writer.setResource(new ClassPathResource("familyData.xml"));
Map<String, String> aliasesMap = new HashMap<String, String>();
aliasesMap.put("family", "Test_example.family");
XStreamMarshaller marshaller = new XStreamMarshaller();
marshaller.setAliases(aliasesMap);
writer.setMarshaller(marshaller);
writer.setRootTagName("familyData");
writer.setOverwriteOutput(true);
return writer;
}
#Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.<family, family> chunk(10)
.reader(reader())
.writer(writer())
.build();
}
#Bean
public Job exportFamilyJob() {
return jobBuilderFactory.get("exportFamilyJob")
.incrementer(new RunIdIncrementer())
.flow(step1())
.end()
.build();
}
}
//family class
public class family {
int id;
String name;
String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String saySomething () {
return "my name is :" + name + " " + description + " " + id;
}
}
You need to use FileSystemResource instead of ClasspathResource in the writer:
writer.setResource(new FileSystemResource("familyData.xml"));
I m having null pointer exception in sessionFactory when i try to use DI in sessionFactory I have to turn spring 3 project into Spring 4 with no xml. I dont know what the problem i m facing, SessionFactory doesnot autowired at all. when i try to test case generic doa Add Method
here is my Configuration File for bean
#Configuration
#EnableTransactionManagement
#EnableWebMvc
#ComponentScan(basePackages = "io.github.bibekshakya35.ehealth")
public class EhealthCofiguration {
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean(name = "dataSource")
public javax.sql.DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/ehealth");
dataSource.setUsername("test");
dataSource.setPassword("test123");
return dataSource;
}
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(javax.sql.DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.scanPackages("io.github.bibekshakya35.ehealth.model");
sessionBuilder.addProperties(getHibernateProperties());
return sessionBuilder.buildSessionFactory();
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.put("hibernate.hbm2ddl.auto", "update");
return properties;
}
#Autowired
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(
SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(
sessionFactory);
return transactionManager;
}
}
to load this class i have created
public class EhealthWebAppIntializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(EhealthCofiguration.class);
ServletRegistration.Dynamic dispatcher =servletContext.addServlet("SpringDispatcher", new DispatcherServlet(applicationContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
this is my generic doa class where i m injecting SessionFactory when it try to access sessionFactory.getCurrentSession(); NPE is occur,
#Repository
#Transactional
public class HibernateDAO<T extends Serializable> implements IGenericDao<T> {
private Class<T> clazz;
Session session;
#Autowired
SessionFactory sessionFactory;
private static final Logger LOG = Logger.getLogger(HibernateDAO.class.getName());
#Override
public void setClazz(Class<T> clazzToSet) {
this.clazz = clazzToSet;
}
#Override
public void create(T entity) {
session = getCurrentSession();
LOG.log(Level.INFO, "inside create entity and you just bind your session to the current one{0}", session.toString());
session.saveOrUpdate(entity);
LOG.info("saved");
session.flush();
session.refresh(entity);
}
protected Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}
Here is my stack trace for NPE
Exception in thread "main" java.lang.NullPointerException
at io.github.bibekshakya35.ehealth.DAO.genericdao.HibernateDAO.getCurrentSession(HibernateDAO.java:115)
at io.github.bibekshakya35.ehealth.DAO.genericdao.HibernateDAO.create(HibernateDAO.java:85)
at io.github.bibekshakya35.ehealth.service.impl.user.main(user.java:46)
here is my user entity
#Entity
#Table(name = "users")
public class User implements Serializable, AbstractEntity {
#Id
#Column(name = "username",unique = true)
private String userName;
#NotNull(message = "password cannot be empty")
#Column(name = "users_password")
private String userPassword;
#Embedded
private UserProfile userProfile;
#Embedded
private AuditInfo auditInfo;
#Enumerated(EnumType.STRING)
private UserType userType;
#Column(name = "is_active")
private boolean active = true;
//getter n setter
}
In chat, You provided me with this code :
public static void main(String[] args) {
User user = new User();
IGenericDao<User> iGenericDao = new HibernateDAO<>();
user.setUserName("bibekshakya35");
user.setUserPassword("ros3");
user.setUserType(UserType.GUEST);
user.setActive(true);
UserProfile userProfile = new UserProfile();
userProfile.setAge(21);
userProfile.setBasicInfo("kdhsa");
userProfile.setEmailId("dsadas#gmail.com");
userProfile.setUserGender(UserGender.Male);
userProfile.setFullname("bibek shakya");
userProfile.setMobileNumber("45454545");
userProfile.setLandLineNumber("445444");
userProfile.setUserProfilePic("index.jsp");
user.setUserProfile(userProfile);
AuditInfo auditInfo = new AuditInfo();
auditInfo.setCreatedOn(new Date());
auditInfo.setModifiedOn(new Date());
auditInfo.setVerifiedOn(new Date());
user.setAuditInfo(auditInfo);
iGenericDao.create(user);
}
Cause of error:
As You are creating the new HibernateDAO instance like this IGenericDao<User> iGenericDao = new HibernateDAO<>(); This is creating the problem.
In the case where You are using annotations, creating new instance manually ,usually causes the above mentioned error.
Reason of error:
Spring can only autowire beans that it manages; if you call new to create a bean yourself, #Autowired fields don't get filled in (and methods like #PostConstruct aren't called).
Solution:
You need to add #autowired to the HibernateDAO which will instantiate it with the exact class which includes the real #Autowired SessionFactory.
Example:
Usually we do it in the class which is itself annotated with annotations like #Controller or #Service.
Like this
#Controller
#RequestMapping(value="/someURL")
public class mainClass {
#Autowired
HibernateDAO abc;
//Code (methods) to test Your CRUD Operations
}
Im trying to use Spring and JPA. I have a table in Oracle of which few of the fields are RAW(16 BYTE) type. My entity looks like following:
#Entity
#Table(name = "testTable")
public class TestTable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID")
#Type(type = "uuid-binary")
private UUID id;
#Column(name = "TABLE_ID")
#Type(type = "uuid-binary")
private UUID tableId;
#Column(name = "STATUS")
private String status;
My repository class looks like the following:
#Repository
public interface TestRepository extends JpaRepository<TestTable, UUID> {
TestTable getTestTableByTableId(#Param("table_id") UUId table_id);
}
The column i'm trying to mark as #Param is not primary key. I have enabled JPA Repositories on configuration file with #EnableJpaRepositories as follows:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackageClasses = { TestRepository.class })
#EnableJpaAuditing
public class JpaConfig {
#Bean(name="entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
Map<String, Object> jpaProperties = new HashMap<>();
jpaProperties.put("eclipselink.weaving", "false");
jpaProperties.put("eclipselink.logging.parameters", "true");
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(this.getDataSource());
entityManagerFactoryBean.setPackagesToScan("com.test.entity");
entityManagerFactoryBean.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
entityManagerFactoryBean.setJpaVendorAdapter(this.vendorAdapter());
entityManagerFactoryBean.setJpaPropertyMap(jpaProperties);
return entityManagerFactoryBean;
}
#Bean
public JpaVendorAdapter vendorAdapter() {
EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
vendorAdapter.setDatabase(Database.ORACLE);
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public DriverManagerDataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
//datasource properties here
return dataSource;
}
#Bean()
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(this.entityManagerFactoryBean().getObject());
return transactionManager;
}
when i autowire the repository in my controller and invoke the method defined in the repository, JPA creates SQL in the background and tried to bind the parameter, but it is binding an object reference instead of UUID as follows:
[EL Fine]: sql: 2016-08-10 09:17:22.306--ServerSession(1292029763)--Connection(678757862)--SELECT ID, TABLE_ID, STATUS FROM TESTTABLE WHERE (TABLE_ID= ?)
bind => [[B#2f6964a4]
My question is why is it binding it as an object? and how would I resolve it? thanks in advance.
I am getting LazyInitializationException while using createQuery(), load() or get() methods. Configuration is based on annotations.
This is exception which I am getting:
Method threw 'org.hibernate.LazyInitializationException' exception. Cannot evaluate lt.package.to.Setting_$$_jvstfff_0.toString()
Schema structure:
CREATE TABLE IF NOT EXISTS `Settings` (
`key` varchar(255) COLLATE utf8_lithuanian_ci NOT NULL,
`value` varchar(255) COLLATE utf8_lithuanian_ci DEFAULT NULL,
PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_lithuanian_ci;
PersistenceConfig.java
#Configuration
#ComponentScan(basePackages= {"lt.setkus.sandbox.persistence"})
#EnableTransactionManagement
#PropertySource({"/WEB-INF/properties/configuration.properties"})
public class PersistenceConfig {
#Autowired
private Environment environment;
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", environment.getProperty("hibernate.hbm2ddl.auto"));
properties.setProperty("hibernate.dialect", environment.getProperty("hibernate.dialect"));
properties.setProperty("hibernate.globally_quoted_identifiers", "true");
return properties;
}
#Bean
public LocalSessionFactoryBean provideSessionFactoryBean() {
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(getDataSource());
localSessionFactoryBean.setPackagesToScan("lt.setkus.sandbox.persistence.domain");
localSessionFactoryBean.setHibernateProperties(getHibernateProperties());
return localSessionFactoryBean;
}
#Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getProperty("jdbc.driver"));
dataSource.setUrl(environment.getProperty("jdbc.url"));
dataSource.setUsername(environment.getProperty("jdbc.user"));
dataSource.setPassword(environment.getProperty("jdbc.password"));
return dataSource;
}
#Bean
#Autowired
public HibernateTransactionManager provideTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager hibernateTransactioManager = new HibernateTransactionManager();
hibernateTransactioManager.setSessionFactory(sessionFactory);
return hibernateTransactioManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor provideExceptionTranslationPostProcessor() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public PostItemRepository postItemRepository() {
return new FacebookPostRepository();
}
#Bean
public PostPersistenceService postPersistenceService(PostItemRepository postItemRepository) {
return new PostPersistenceEventHandler(postItemRepository);
}
#Bean
public SettingRepository provideSettingRepository() {
return new SettingDatabaseRepository();
}
#Bean
public SettingPersistenceService provideSettingPersistenceService(SettingRepository settingRepository) {
return new SettingPersistenceEventHandler(settingRepository);
}
}
Domain model class
#Entity
#Table(name = "settings")
public class Setting implements Serializable {
#Id
#Column(name = "key", unique = true)
private String key;
#Column(name = "value")
private String value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public SettingDetails toSettingDetails() {
SettingDetails settingDetails = new SettingDetails();
BeanUtils.copyProperties(this, settingDetails);
return settingDetails;
}
public static Setting fromSettingDetails(SettingDetails settingDetails) {
Setting setting = new Setting();
BeanUtils.copyProperties(settingDetails, setting);
return setting;
}
}
Service layer
public class SettingDatabaseRepository implements SettingRepository {
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public Setting get(final String key) {
return (Setting)sessionFactory.getCurrentSession().get(Setting.class, key);
}
}
I really can't find any mistake which is causing these exceptions. What I am doing wrong?
The proper way to get object by its id will be
public Setting get(final String key) {
return (Setting) sessionFactory.getCurrentSession().get(Setting.class, key);
}