Xml file contains no data after i run my application - java

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"));

Related

Cant add data to database, 404 not found for mapping

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
);

Spring Jpa repository find all returns empty list

I have connected spring boot to an MySQL database running on a VPS. I've mapped the entity class, repository, service and controller. But when calling the get method for "findAll" I get an empty list in postman. When I query the table in MySQL workbench I do get data, so its not empty.
Did I miss something?
My entity class:
#Entity
public class Requests {
#Id
#Column
private Long id;
#Column
private Long url_id;
#Column
private Date timestamp;
#Column
private String method;
#Column
private String document;
#Column
private String mime_type;
#Column
private char is_html;
#Column
private int status_code;
#Column
private String reason;
#Column
private String cookies;
#Column
private String request;
#Column
private String response;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUrl_id() {
return url_id;
}
public void setUrl_id(Long url_id) {
this.url_id = url_id;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getDocument() {
return document;
}
public void setDocument(String document) {
this.document = document;
}
public String getMime_type() {
return mime_type;
}
public void setMime_type(String mime_type) {
this.mime_type = mime_type;
}
public char getIs_html() {
return is_html;
}
public void setIs_html(char is_html) {
this.is_html = is_html;
}
public int getStatus_code() {
return status_code;
}
public void setStatus_code(int status_code) {
this.status_code = status_code;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getCookies() {
return cookies;
}
public void setCookies(String cookies) {
this.cookies = cookies;
}
public String getRequest() {
return request;
}
public void setRequest(String request) {
this.request = request;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
My reposiroty:
public interface RequestsRepository extends JpaRepository<Requests, Long> {
}
My service:
#Service
public class RequestsService {
private final RequestsRepository requestsRepository;
public RequestsService(RequestsRepository requestsRepository) {
this.requestsRepository = requestsRepository;
}
public List<RequestsDTO> findAll() {
return requestsRepository.findAll()
.stream()
.map(requests -> mapToDTO(requests, new RequestsDTO()))
.collect(Collectors.toList());
}
private RequestsDTO mapToDTO(final Requests requests, final RequestsDTO requestsDTO) {
requestsDTO.setId(requests.getId());
requestsDTO.setUrl_id(requests.getUrl_id());
requestsDTO.setTimestamp(requests.getTimestamp());
requestsDTO.setMethod(requests.getMethod());
requestsDTO.setDocument(requests.getDocument());
requestsDTO.setMime_type(requests.getMime_type());
requestsDTO.setIs_html(requests.getIs_html());
requestsDTO.setStatus_code(requests.getStatus_code());
requestsDTO.setReason(requests.getReason());
requestsDTO.setCookies(requests.getCookies());
requestsDTO.setRequest(requests.getRequest());
requestsDTO.setResponse(requests.getResponse());
return requestsDTO;
}
private Requests mapToEntity(final RequestsDTO requestsDTO, final Requests requests) {
requests.setId(requestsDTO.getId());
requests.setUrl_id(requestsDTO.getUrl_id());
requests.setTimestamp(requestsDTO.getTimestamp());
requests.setMethod(requestsDTO.getMethod());
requests.setDocument(requestsDTO.getDocument());
requests.setMime_type(requestsDTO.getMime_type());
requests.setIs_html(requestsDTO.getIs_html());
requests.setStatus_code(requestsDTO.getStatus_code());
requests.setReason(requestsDTO.getReason());
requests.setCookies(requestsDTO.getCookies());
requests.setRequest(requestsDTO.getRequest());
requests.setResponse(requestsDTO.getResponse());
return requests;
}
}
And my controller:
#RestController
#RequestMapping(value = "/api/crawler", produces = MediaType.APPLICATION_JSON_VALUE)
public class RequestsController {
private final RequestsService requestsService;
public RequestsController(RequestsService requestsService) {
this.requestsService = requestsService;
}
#GetMapping
public ResponseEntity<List<RequestsDTO>> getAllRequests() {return ResponseEntity.ok(requestsService.findAll()); }
}
EDIT
My crawler domain config
/**
* Data source for the MySQL crawler database
*/
#Configuration
#EntityScan(basePackages = "cs.crawler.server.projectcs.domain.crawlerdb")
#EnableJpaRepositories(basePackages = "cs.crawler.server.projectcs.repos.crawlerdb")
#EnableTransactionManagement
public class CrawlerDomainConfig {
#Bean
#ConfigurationProperties("spring.datasource.crawler")
public DataSourceProperties crawlerDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#ConfigurationProperties("spring.datasource.crawler.configuration")
public HikariDataSource secondDataSource(DataSourceProperties secondDataSourceProperties) {
return secondDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
}
My config YAML:
spring:
datasource:
users:
url: ${JDBC_DATABASE_URL:jdbc:h2:mem:projectcs}
username: ${JDBC_DATABASE_USERNAME:sa}
password: ${JDBC_DATABASE_PASSWORD:}
crawler:
url: ${JDBC_DATABASE_URL:jdbc:mysql://VPSIPHERE:3306/darcweb?createDatabaseIfNotExist=false}
username: ${JDBC_DATABASE_USERNAME:root}
password: ${JDBC_DATABASE_PASSWORD:mypassword}
dbcp2:
max-wait-millis: 30000
validation-query: "SELECT 1"
validation-query-timeout: 30
jpa:
hibernate:
ddl-auto: update
open-in-view: false
properties:
hibernate:
jdbc:
lob:
non_contextual_creation: true
id:
new_generator_mappings: true
springdoc:
pathsToMatch: /api/**
You have 2 datasoruce dependencies (mysql and h2). You need to specify which datasource for spring to use - it picks h2 by default which is the reason you don't find anything.
Add following lines to your application.properties file to specify the database:
spring.datasource.url=jdbc:mysql://localhost:3306/DATABASE_NAME
spring.datasource.username=USERNAME
spring.datasource.password=PASSWORD
To use h2 for tests for example you can overwrite application.properties for h2 under your test folder in resources
In case you want to use both databases simultaneously in your application you would need to define both and set them in runtime into your enviroment like shown here:
https://www.baeldung.com/spring-data-jpa-multiple-databases

How to set up database connection in r2dbc?

How to set up a PostgreSQL database connection in r2dbc Spring boot project?
I have tried the below configuration, it connects to the database but it's not returning any values
#Configuration
#EnableR2dbcRepositories
public class DatabaseConfig extends AbstractR2dbcConfiguration {
#Override
public ConnectionFactory connectionFactory() {
return ConnectionFactories.get("r2dbc:postgresql://localhost:5432/sample");
}
/*#Override
public ConnectionFactory connectionFactory() {
return ConnectionFactories.get(new PostgresqlConnectionFactory(
PostgresqlConnectionConfiguration.builder()
.host("localhost")
.port(5432)
.username("postgres")
.password("thirumal")
.database("sample")
.build()););
}*/
}
application.properties
spring.r2dbc.url=r2dbc:postgresql://localhost:5432/sample
spring.r2dbc.username=postgres
spring.r2dbc.password=thirumal
spring.r2dbc.pool.enabled=true
Model
#Data#NoArgsConstructor#AllArgsConstructor#Getter#Setter
#ToString
#Table("public.test")
public class Test implements Serializable{
/**
*
*/
private static final long serialVersionUID = 4205798689305488147L;
#Id//#Column("id")
private Long id;
private String name;
}
Repository
public interface TestRepository extends ReactiveCrudRepository<Test, Long> {
}
REST CONTROLLER:
#GetMapping("/test")
public Mono<Test> test() {
testRepository.findById(3L).subscribe(v->System.out.println("Value: " + v.toString()));
return testRepository.findById(3L);
}
It prints the output in the console but in the JSON, I get only empty braces {}
What is the correct way to configure? Any other configuration is required?
I found the problem. It's Lombok library, I didn't install it in eclipse.
When I created the getter and setter method manually it worked.
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Then, I set up the lombok and used #getter and #setter and it worked.
This configuration works for me, but I use the DatabaseClient instead of the R2dbcRepositories to query the data:
#Configuration
public class DatabaseConfiguration extends AbstractR2dbcConfiguration {
#Override
#Bean
public ConnectionFactory connectionFactory() {
return new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration.builder()
.host("localhost")
.port(5432)
.username("username")
.password("password")
.database("mydb")
.build());
}
}
Then in the repository:
#Repository
public class MyRepository {
#Autowired
private DatabaseClient client;
public Flux<String> getString() {
....
}
}
UPDATE:
If it's connect to the database probably your configuration is right, can you share also the code used to get the data?
It's possible that you are getting the result as Mono or Flux, but not reading from it (try with subscribe()).
Mono<String> mono = db.getData();
mono.subscribe(value -> System.out.println(value));

Add Spring JDBC support based on annotations

I have task to upgrade Map based storage to DB based storage. My project configuration is based on annotations. Could you explain to me which steps should I take to make it happen? And how will change my dao layer code:
public class TicketDao {
Set<Ticket> tickets = new HashSet<>();
public Set<Ticket> getAll() {
return tickets;
}
public void remove(Ticket ticket){
tickets.remove(ticket);
}
public void put(Ticket ticket){
tickets.add(ticket);
}
}
Create db and schema
Configure DataSource and JdbcTemplate. The simpliest configuration:
#Configuration
public class JdbcConfig {
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("");
dataSource.setUrl("");
dataSource.setUsername("");
dataSource.setPassword("");
return dataSource;
}
#Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
}
Inject JdbcTemplate into dao and use it
public class TicketDao {
public static final String DELETE_QUERY = "delete from Ticket where id = ?";
public static final String INSERT_QUERY = "insert into Ticket values(?, ?)";
public static final String GET_ALL_QUERY = "select * from Tickets";
#Autowired
JdbcTemplate jdbcTemplate;
public Set<Ticket> getAll() {
return new HashSet<>(jdbcTemplate.query(GET_ALL_QUERY, new RowMapper<Ticket>() {
#Override
public Ticket mapRow(ResultSet rs, int rowNum) throws SQLException {
Ticket ticket = new Ticket();
ticket.setId(rs.getString(1));
//other fields mapping
return ticket;
}
}));
}
public void remove(Ticket ticket){
jdbcTemplate.update(new PreparedStatementCreator() {
#Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement statement = con.prepareStatement(DELETE_QUERY);
statement.setString(1, ticket.getId());
return statement;
}
});
}
public void put(Ticket ticket){
Object[] values = {ticket.getId(), ticket.getName()};
int[] types = {Types.VARCHAR, Types.VARCHAR};
jdbcTemplate.update(INSERT_QUERY, values, types);
}
}

Method threw 'org.hibernate.LazyInitializationException' exception

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);
}

Categories

Resources