Spring JDBC update without commit - spring

I have a simple table "employee" defined as:
create table employee (id int, name varchar2(40));
I want to write an application to insert values in it and commit only after all values are inserted. Here is my code:
Employee.java:
package com.empl;
public class Employee {
private int id;
private String name;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
EmployeeDAO.java:
package com.empl;
import javax.sql.DataSource;
public interface EmployeeDAO {
public void setDataSource(DataSource dataSource);
public void create(int id, String name);
}
EmployeeJDBCTemplate.java:
package com.empl;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeJDBCTemplate {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public DataSource getDataSource() {
return dataSource;
}
public void create(int id, String name) {
String SQL = "insert into employee (id, name) values (?, ?)";
jdbcTemplateObject.update(SQL, id, name);
}
}
MainApp.java:
package com.empl;
import java.sql.SQLException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String args[]) throws SQLException {
ApplicationContext context = new
ClassPathXmlApplicationContext("Beans.xml");
EmployeeJDBCTemplate employeeJDBCTemplate =
(EmployeeJDBCTemplate) context.getBean("employeeJDBCTemplate");
employeeJDBCTemplate.getDataSource().getConnection().
setAutoCommit(false);
employeeJDBCTemplate.create(1, "E1");
employeeJDBCTemplate.create(2, "E2");
}
}
Beans.xml:
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<bean id = "dataSource" class =
"org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value =
"oracle.jdbc.driver.OracleDriver"></property>
<property name = "url" value =
"jdbc:oracle:thin:#localhost:1521/xe"></property>
<property name = "username" value = "sys as sysdba"></property>
<property name = "password" value = "pass"></property>
</bean>
<bean id = "employeeJDBCTemplate" class =
"com.empl.EmployeeJDBCTemplate">
<property name = "dataSource" ref = "dataSource"></property>
</bean>
</beans>
I executed the code but when I enter SQLPlus and type the rollback; command, the records are still in the table.
I saw related questions but nothing seems to work.

Related

List all DB tables - JPA

I want to list all the tables in my DB using Spring boot and JPA, I have created a DataSource configuration like - configuring-spring-boot-for-oracle and tried -
#Repository
public interface TestRepo extends JpaRepository<Table, Long>{
#Query("SELECT owner, table_name FROM dba_tables")
List<Table> findAllDB();
}
And my Table Entity -
#Entity
public class Table {
String owner;
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
And got -
No identifier specified for entity: com.siemens.plm.it.aws.connect.repos.Table
So how do I query for DB tables names?
So far my main -
#SpringBootApplication
public class AwsFileUploadApplication implements CommandLineRunner{
#Autowired
DataSource dataSource;
#Autowired
TestRepo repo;
public static void main(String[] args) {
//https://wwwtest.plm.automation.siemens.com/subsadmin/app/products
SpringApplication.run(AwsFileUploadApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("DATASOURCE = " + dataSource); //some value - ds init sucess
List<Table> findAllDB = repo.findAllDB();
System.out.println(findAllDB);
}
}
When removing #Entity from Table - Not a managed type: class com.siemens.plm.it.aws.connect.repos.Table.
I print all my tables and columns using JDBC:
#Autowired
protected DataSource dataSource;
public void showTables() throws Exception {
DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
ResultSet tables = metaData.getTables(null, null, null, new String[] { "TABLE" });
while (tables.next()) {
String tableName=tables.getString("TABLE_NAME");
System.out.println(tableName);
ResultSet columns = metaData.getColumns(null, null, tableName, "%");
while (columns.next()) {
String columnName=columns.getString("COLUMN_NAME");
System.out.println("\t" + columnName);
}
}
}
If you look at the getTables API you can see how to refine the search of tables.

Spring boot H2 database application

I have created a sample project with following code. Even if i am not providing table create statement in the data.sql, it is creating the table. how to stop that. Sample code is present below
Can you please let me know what I am doing wrong? I have removed the import statements below as the post was not allowing to put so much code here.
package com.example.demo;
// Model class
#Entity
#Table(name="reservation")
public class Reservation {
#Id
private Long id;
#Column(name="user_id")
private Long userId;
#Column(name="party_size")
private int partySize;
#Column(name="restaurant_id")
private Long restaurantId;
#Column(name="date")
private LocalDateTime dt;
public Reservation() {}
public Reservation(Long id, Long userId, int partySize) {
this.id = id;
this.userId = userId;
this.partySize = partySize;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public int getPartySize() {
return partySize;
}
public void setPartySize(int partySize) {
this.partySize = partySize;
}
public Long getRestaurantId() {
return restaurantId;
}
public void setRestaurantId(Long restaurantId) {
this.restaurantId = restaurantId;
}
public LocalDateTime getDt() {
return dt;
}
public void setDt(LocalDateTime dt) {
this.dt = dt;
}
}
package com.example.demo;
#SpringBootApplication
public class ReservationApp {
public static void main(String[] args) {
SpringApplication.run(ReservationApp.class, args);
}
}
package com.example.demo;
#RestController
#RequestMapping("/v1")
public class ReservationController {
#Autowired
private ReservationService reservationService;
// ------------ Retrieve all reservations ------------
#RequestMapping(value = "/reservations", method = RequestMethod.GET)
public List getAllReservations() {
return reservationService.getAllReservations();
}
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
public interface ReservationRepository extends CrudRepository<Reservation,String> {
}
package com.example.demo;
#Service
public class ReservationService {
#Autowired
private ReservationRepository reservationRepository;
// Retrieve all rows from table and populate list with objects
public List getAllReservations() {
List reservations = new ArrayList<>();
reservationRepository.findAll().forEach(reservations::add);
return reservations;
}
}
try to remove the spring boot hibernate configuration
spring.jpa.hibernate.ddl-auto = update
Which is able of creating/updating the database schema from entities
To disable automatic DDL generation, set the following property to false in application.properties:
spring.jpa.generate-ddl = false
For more information and fine-grained control, please see the documentation.
Set the ddl generation to none in the application.properties:
spring.jpa.hibernate.ddl-auto=none

What are the depencencies to be added to get the XML output in spring-mvc?

What are the maven dependencies need to be added to get the XML output without configuring content negotiation view resolver and managers. By using the default Message Converters based on jars on classpath (output based on accept headers). I am able to get the JSON output by having jackson-databind dependency on the classpath. For XML I am using
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
dependencies - I am unable to get the XML output. DO I need configure any Marshallers like Jaxb2Marsahllar as a bean in the configuration file. Can Any post the maven dependencies for JAXB2.
My Entity class:
package com.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name = "Employee")
#XmlRootElement
public class Employee {
public Employee() {
}
public Employee(Integer empno, String name, String dept, Double salary) {
this.empno = empno;
this.name = name;
this.dept = dept;
this.salary = salary;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer empno;
#Size(min = 1, max = 30)
#NotEmpty
private String name;
#NotEmpty
#Size(min = 1, max = 30)
private String dept;
/*
* #NotEmpty - cannot be set to double - supports String Collection Map
* arrays
*/
private Double salary;
#XmlAttribute
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
#XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlElement
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
#XmlElement
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee [empno=" + empno + ", name=" + name + ", dept=" + dept
+ ", salary=" + salary + "]";
}
}
My Controller Class:
#Controller
public class EmployeeController {
#Autowired
EmployeeRepository employeeRepository;
#RequestMapping(value = "/employees", method=RequestMethod.GET,
produces= {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public #ResponseBody List<Employee> findAllXml(){
return employeeRepository.findAll();
}
}
Please Can any one say Whether the dependencies are enough ? What needs to be added..
put #XMLElement on set methods.
public Integer getEmpno() {
return empno;
}
#XmlAttribute
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
or you can use Spring Marshalling View of spring-oxm.jar
<bean id="xmlViewer"
class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.model.Employee</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
Update:1
Also findAll is returning list that list needs to be accomodated in a parent tag like
<Employees>
<Employee />
<Employee />
</Employees>
so you need to define a class that has an #XMLElement entity as List<Employees> create object of it put the data in it and return that object.
I found the answer to 406 exception
Problem was needed an extra configuration for Message Converters for XML output.
For XML Output, we need to Added a Message Converter to the list of Message converters of RequestMappingHandlerAdapter
But for JSON we dont need to do this explictly, based on the jackson-databind dependencies on the classpath, we can able get the JSON output. But for xml , we need to add a message converter (MarshallingHttpMessageConverter) .
Example: Using Java Based Config: configuring RequestMappingHandlerAdapter as a bean and adding required Message Converters...
#Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter();
List<HttpMessageConverter<?>> converters = new ArrayList();
converters.add(new MarshallingHttpMessageConverter(
new XStreamMarshaller()));
converters.add(new MappingJackson2HttpMessageConverter());
adapter.setMessageConverters(converters);
return adapter;
}
I am using XStream Marshaller, so need to add its dependencies as well
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.8</version>
</dependency>
Example Tests:
#Test
public void testXml() throws Exception {
this.mvc.perform(get("/employees/xml").accept(APPLICATION_XML))
.andDo(print())
.andExpect(content().contentType("application/xml"));
}
#Test
public void testJson() throws Exception {
this.mvc.perform(get("/employees/json").accept(APPLICATION_JSON))
.andDo(print())
.andExpect(content().contentType("application/json"));
}
Please post if you know any other way of doing this.
useful link: Spring XML 406 error

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'std' defined in file

package com.nareshit.beans;
public class Address {
private String city,state;
public String toString()
{
return "\n city:"+city+"\nstate:"+state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
package com.nareshit.clients;
import java.awt.Container;
import java.beans.Beans;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import com.nareshit.beans.Student;
public class Test {
public static void main(String[] args)
{
BeanFactory factory=new XmlBeanFactory(new ClassPathResource("MyBeans.xml"));
Student std1=(Student)factory.getBean("std");
std1.getStudentDetails();
}
}
package com.nareshit.beans;
public class Student {
private int sid;
private String name;
private String address;
public void getStudentDetails()
{
System.out.println("student id:"+sid);
System.out.println("student name:"+name);
System.out.println("student address:"+address);
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="std" class="com.nareshit.beans.Student">
<property name="std" value="1001"/>
<property name="name" value="mitu"/>
<property name="address" ref="addressObj"/>
</bean>
<bean id="addressObj" class="com.nareshit.beans.Address">
<property name="city" value="bam"/>
<property name="state" value="odisha"/>
</bean>
</beans>
This is the spring setter injection prog. where i am getting error:
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'std' defined in file("")
how to solve it?
Please see com.nareshit.beans.Student class. It is having one property named as address which is a type of String. When you are writing the XML,
you are giving one reference type of com.nareshit.beans.Address.
Solution :
1. You can give a String value in the XML for address property.like
ddress property like
<bean id="std" class="com.nareshit.beans.Student">
<property name="std" value="1001"/>
<property name="name" value="mitu"/>
<property name="address" value="SOME ADDRESS"/>
</bean>
2. You can change the type of address property in Student Class like
public class Student{
Address address;
//declaration of rest property
//Some Boiler Plate Code
}

#XmlPath not working

#XmlPath is not working.
Customer.java
import org.eclipse.persistence.oxm.annotations.XmlPath;
#XmlRootElement(name= "Customer")
public class Customer {
private String CustomerId;
private String organizationCode;
private Extn extn;
private String organizationName;
private int reset;
private CustomerSchedulingPreferences customerSchedulingPreferences;
private ArrayList<RestrictedState> restrictedStateList;
#XmlAttribute
public String getCustomerId() {
return CustomerId;
}
public void setCustomerId(String customerId) {
CustomerId = customerId;
}
#XmlAttribute
public String getOrganizationCode() {
return organizationCode;
}
public void setOrganizationCode(String organizationCode) {
this.organizationCode = organizationCode;
}
#XmlElement(name="Extn")
public Extn getExtn() {
return extn;
}
public void setExtn(Extn extn) {
this.extn = extn;
}
#XmlPath("BuyerOrganization/#OrganizationName")
public String getOrganizationName() {
return organizationName;
}
public void setOrganizationName(String organizationName) {
this.organizationName = organizationName;
}
#XmlPath("BuyerOrganization/Extn/USSCORestrictedStateList")
#XmlElement(name = "USSCORestrictedState")
public ArrayList<RestrictedState> getRestrictedStateList() {
return restrictedStateList;
}
public void setRestrictedStateList(ArrayList<RestrictedState> restrictedStateList) {
this.restrictedStateList = restrictedStateList;
}
#XmlPath("BuyerOrganization/Extn/USSCORestrictedStateList/#Reset")
public int getReset() {
return reset;
}
public void setReset(int reset) {
this.reset = reset;
}
#XmlElement(name="CustomerSchedulingPreferences")
public CustomerSchedulingPreferences getCustomerSchedulingPreferences() {
return customerSchedulingPreferences;
}
public void setCustomerSchedulingPreferences(
CustomerSchedulingPreferences customerSchedulingPreferences) {
this.customerSchedulingPreferences = customerSchedulingPreferences;
}
}
Client.java
import javax.xml.transform.stream.StreamResult;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
public class Client
{
public static void main(String[] args)throws IOException
{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Marshaller marshaller = (Marshaller)context.getBean("jaxbMarshallerBean");
Customer customer=new Customer();
customer.setCustomerId("12345");
customer.setOrganizationCode("SUPPLY");
Extn extn = new Extn();
extn.setExtnBillCreditCode("000");
extn.setExtnBillSubscriptionId("132131");
customer.setExtn(extn);
RestrictedState resState1= new RestrictedState();
resState1.setOrgCode("952121");
resState1.setRestrictedStateCode("IN");
RestrictedState resState2= new RestrictedState();
resState2.setOrgCode("60325");
resState2.setRestrictedStateCode("IL");
ArrayList<RestrictedState> restrictedStateList = new ArrayList<RestrictedState>();
restrictedStateList.add(resState1);
restrictedStateList.add(resState2);
CustomerSchedulingPreferences custSchedPref = new CustomerSchedulingPreferences();
custSchedPref.setIsLineShipComplete("Y");
custSchedPref.setIsLineShipSingleNode("N");
custSchedPref.setOptimizationType("03");
customer.setCustomerSchedulingPreferences(custSchedPref);
customer.setRestrictedStateList(restrictedStateList);
marshaller.marshal(customer, new StreamResult(new FileWriter("customer.xml")));
System.out.println("XML Created Sucessfully");
}
}
applicationContext.Xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
<oxm:jaxb2-marshaller id="jaxbMarshallerBean">
<oxm:class-to-be-bound name="com.javatpoint.Customer"/>
</oxm:jaxb2-marshaller>
</beans>
Structure of Output needed :
<Customer CustomerID="952121" OrganizationCode="SUPPLY" >
<Extn ExtnBillCreditCode="000" ExtnBillSubscriptionID="952121" />
<BuyerOrganization OrganizationName="Buy.com1" >
<Extn>
<USSCORestrictedStateList Reset="Y">
<USSCORestrictedState OrganizationCode="952121" RestrictedStateCode="IN"/>
</USSCORestrictedStateList>
</Extn>
</BuyerOrganization>
<CustomerSchedulingPreferences IsLineShipComplete="" IsLineShipSingleNode="" />
</Customer>
================================================================================
Please help me in resolving this:
Currently i am getting output like below :
<Customer organizationCode="SUPPLY" customerId="12345">
<CustomerSchedulingPreferences IsLineShipSingleNode="N" IsLineShipComplete="Y"/>
<Extn ExtnBillSubscriptionID="132131" ExtnBillCreditCode="000"/>
<reset>0</reset>
<USSCORestrictedState restrictedStateCode="IN" OrganizationCode="952121"/>
<USSCORestrictedState restrictedStateCode="IL" OrganizationCode="60325"/>
</Customer>
To leverage the #XmlPath extension you need to be using EclipseLink MOXy as your JAXB provider.
eclipselink.jar on your classpath
a jaxb.properties file in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Below is a link that will help set this up:
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/Spring

Resources