Spring ORM – Useful Resources

Spring ORM – Useful Resources ”; Previous Next The following resources contain additional information on Spring ORM. Please use them to get more in-depth knowledge on this topic. Useful Links on Spring ORM Spring Source − Find latest news about Spring Framework, download section and all about Spring. Spring Framework Documentation − Complete Spring Framework reference covering all the modules. Oracle”s Site on JDBC − Sun Developer Network giving link on JDBC material. MySQL Connector/J − MySQL Connector/J is the official JDBC driver for MySQL. The JavaTM Tutorials − The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications. JavaTM 2 SDK, Standard Edition − Official site for JavaTM 2 SDK, Standard Edition Free Java Download − Download Java for your desktop computer now! Java Technology Reference − Sun Microsystem”s official website listing down all the API documentation, latest Java Technologies, Books and other resource. Useful Books on Spring ORM To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Spring WS – Discussion

Discuss Spring Web Services ”; Previous Next Spring Web Services (Spring-WS) is one of the project developed by the Spring Community. Its prime focus is to create document-driven Web Services. The Spring Web Services project facilitates contract-first SOAP service development, provides multiple ways to create flexible web services, which can manipulate XML payloads in multiple ways. Being Spring based, Spring Web Services uses Spring Concepts like Dependency Injection and Configurations seamlessly. Spring-WS requires Spring 3.0 version. Spring Framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003. This tutorial has been written based on the Spring Framework Version 4.1.6 released in March 2015. Print Page Previous Next Advertisements ”;

Spring MVC – Checkbox

Spring MVC – Checkbox Example ”; Previous Next The following example describes how to use a Single Checkbox in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name HelloWeb under a package com.tutorialspointas explained in the Spring MVC – Hello World Example chapter. 2 Create Java classes User, UserController under the com.tutorialspointpackage. 3 Create a view files user.jsp, users.jsp under jsp sub-folder. 4 The final step is to create the content of the source and configuration files and export the application as explained below. User.java package com.tutorialspoint; public class User { private String username; private String password; private String address; private boolean receivePaper; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public boolean isReceivePaper() { return receivePaper; } public void setReceivePaper(boolean receivePaper) { this.receivePaper = receivePaper; } } UserController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.ui.ModelMap; @Controller public class UserController { @RequestMapping(value = “/user”, method = RequestMethod.GET) public ModelAndView user() { return new ModelAndView(“user”, “command”, new User()); } @RequestMapping(value = “/addUser”, method = RequestMethod.POST) public String addUser(@ModelAttribute(“SpringWeb”)User user, ModelMap model) { model.addAttribute(“username”, user.getUsername()); model.addAttribute(“password”, user.getPassword()); model.addAttribute(“address”, user.getAddress()); model.addAttribute(“receivePaper”, user.isReceivePaper()); return “users”; } } Here, for the first service method user(), we have passed a blank User object in the ModelAndView object with name “command”, because the spring framework expects an object with name “command”, if you are using <form:form> tags in your JSP file. So, when the user() method is called it returns the user.jsp view. The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the “users” view will be returned from the service method, which will result in rendering the users.jsp. user.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <body> <h2>User Information</h2> <form:form method = “POST” action = “/HelloWeb/addUser”> <table> <tr> <td><form:label path = “username”>User Name</form:label></td> <td><form:input path = “username” /></td> </tr> <tr> <td><form:label path = “password”>Age</form:label></td> <td><form:password path = “password” /></td> </tr> <tr> <td><form:label path = “address”>Address</form:label></td> <td><form:textarea path = “address” rows = “5” cols = “30” /></td> </tr> <tr> <td><form:label path = “receivePaper”>Subscribe Newsletter</form:label></td> <td><form:checkbox path = “receivePaper” /></td> </tr> <tr> <td colspan = “2”> <input type = “submit” value = “Submit”/> </td> </tr> </table> </form:form> </body> </html> Here, we are using <form:checkboxes /> tag to render an HTML checkbox box. For example − <form:checkbox path=”receivePaper” /> It will render following HTML content. <input id=”receivePaper1″ name = “receivePaper” type = “checkbox” value = “true”/> <input type = “hidden” name = “_receivePaper” value = “on”/> users.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <body> <h2>Submitted User Information</h2> <table> <tr> <td>Username</td> <td>${username}</td> </tr> <tr> <td>Password</td> <td>${password}</td> </tr> <tr> <td>Address</td> <td>${address}</td> </tr> <tr> <td>Subscribed to Newsletter</td> <td>${receivePaper}</td> </tr> </table> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL – http://localhost:8080/HelloWeb/user and we will see the following screen if everything is fine with the Spring Web Application. After submitting the required information, click on the submit button to submit the form. We will see the following screen if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;

XStream – Converters

XStream – Converters ”; Previous Next XStream converters are the key components of the XStream library, which are responsible to convert an object to XML and vice versa. XStream provides numerous converters for common types such as primitives, String, File, Collections, arrays, and Dates. Using Converter Let us use a SingleValueConvertor whose purpose is to convert an object into a single string. We will use SingleValueConvertor to write an object as attribute string. Create a Converter class NameConverter implements SingleValueConverter { public Object fromString(String name) { String[] nameparts = name.split(“,”); return new Name(nameparts[0], nameparts[1]); } public String toString(Object name) { return ((Name)name).getFirstName() + “,” + ((Name)name).getLastName(); } public boolean canConvert(Class type) { return type.equals(Name.class); } } Register a Converter xstream.registerConverter(new NameConverter()); Example without Converter Let us first test the code without converter in XStream. Create a java class file named XStreamTester in C:>XStream_WORKSPACEcomtutorialspointxstream. File: XStreamTester.java package com.tutorialspoint.xstream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.io.xml.StaxDriver; public class XStreamTester { public static void main(String args[]) { XStreamTester tester = new XStreamTester(); XStream xstream = new XStream(new StaxDriver()); Student student = tester.getStudentDetails(); xstream.autodetectAnnotations(true); //Object to XML Conversion String xml = xstream.toXML(student); System.out.println(formatXml(xml)); } private Student getStudentDetails() { Student student = new Student(“Mahesh”,”Parashar”); return student; } public static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, “yes”); serializer.setOutputProperty(“{http://xml.apache.org/xslt}indent-amount”, “2”); Source xmlSource = new SAXSource(new InputSource( new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray()); } catch(Exception e) { return xml; } } } @XStreamAlias(“student”) class Student { @XStreamAlias(“name”) @XStreamAsAttribute private Name studentName; public Student(String firstName, String lastName) { this.studentName = new Name(firstName, lastName); } public Name getName() { return studentName; } } class Name { private String firstName; private String lastName; public Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } Verify the Result Compile the classes using javac compiler as follows − C:XStream_WORKSPACEcomtutorialspointxstream>javac XStreamTester.java Now run the XStreamTester to see the result − C:XStream_WORKSPACEcomtutorialspointxstream>java XStreamTester Verify the output as follows − <?xml version = “1.0” encoding = “UTF-8”?> <student> <name> <firstName>Mahesh</firstName> <lastName>Parashar</lastName> </name> </student> Example with Converter Let us now test the code with converter in XStream. Create a java class file named XStreamTester in C:>XStream_WORKSPACEcomtutorialspointxstream. File: XStreamTester.java package com.tutorialspoint.xstream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.converters.SingleValueConverter; import com.thoughtworks.xstream.io.xml.StaxDriver; public class XStreamTester { public static void main(String args[]) { XStreamTester tester = new XStreamTester(); XStream xstream = new XStream(new StaxDriver()); Student student = tester.getStudentDetails(); xstream.autodetectAnnotations(true); xstream.registerConverter(new NameConverter()); //Object to XML Conversion String xml = xstream.toXML(student); System.out.println(formatXml(xml)); } private Student getStudentDetails() { Student student = new Student(“Mahesh”,”Parashar”); return student; } public static String formatXml(String xml) { try { Transformer serializer = SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, “yes”); serializer.setOutputProperty(“{http://xml.apache.org/xslt}indent-amount”, “2”); Source xmlSource = new SAXSource(new InputSource( new ByteArrayInputStream(xml.getBytes()))); StreamResult res = new StreamResult(new ByteArrayOutputStream()); serializer.transform(xmlSource, res); return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray()); } catch(Exception e) { return xml; } } } @XStreamAlias(“student”) class Student { @XStreamAlias(“name”) @XStreamAsAttribute private Name studentName; public Student(String firstName, String lastName) { this.studentName = new Name(firstName, lastName); } public Name getName() { return studentName; } } class Name { private String firstName; private String lastName; public Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } class NameConverter implements SingleValueConverter { public Object fromString(String name) { String[] nameparts = name.split(“,”); return new Name(nameparts[0], nameparts[1]); } public String toString(Object name) { return ((Name)name).getFirstName() + “,” + ((Name)name).getLastName(); } public boolean canConvert(Class type) { return type.equals(Name.class); } } Verify the Result Compile the classes using javac compiler as follows − C:XStream_WORKSPACEcomtutorialspointxstream>javac XStreamTester.java Now run the XStreamTester to see the result − C:XStream_WORKSPACEcomtutorialspointxstream>java XStreamTester Verify the output as follows − <?xml version = “1.0” encoding = “UTF-8”?> <student name = “Mahesh,Parashar”/> Custom Converter Print Page Previous Next Advertisements ”;

Spring DI – Collections Setter

Spring DI – Collections Setter ”; Previous Next You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean. Now what if you want to pass plural values like Java Collection types such as List, Set, Map, and Properties. To handle the situation, Spring offers following types of collection configuration elements which are as follows − Sr.No Element & Description 1 <list> This helps in wiring ie injecting a list of values, allowing duplicates. 2 <set> This helps in wiring a set of values but without any duplicates. 3 <props> This can be used to inject a collection of name-value pairs where the name and value are both Strings. You can use either <list> or <set> to wire any implementation of java.util.Collection or an array. In this example, we”re showcasing passing direct values of the collection elements. Example The following example shows a class JavaCollection that is using collections as dependency injected using setters. Let”s update the project created in Spring DI – Create Project chapter. We”re adding following files − JavaCollection.java − A class containing a collections as dependency. MainApp.java − Main application to run and test. Here is the content of JavaCollection.java file − package com.tutorialspoint; import java.util.*; public class JavaCollection { List<String> addressList; Set<String> addressSet; Properties addressProp; // a setter method to set List public void setAddressList(List<String> addressList) { this.addressList = addressList; } // prints and returns all the elements of the list. public List<String> getAddressList() { System.out.println(“List Elements :” + addressList); return addressList; } // a setter method to set Set public void setAddressSet(Set<String> addressSet) { this.addressSet = addressSet; } // prints and returns all the elements of the Set. public Set<String> getAddressSet() { System.out.println(“Set Elements :” + addressSet); return addressSet; } // a setter method to set Property public void setAddressProp(Properties addressProp) { this.addressProp = addressProp; } // prints and returns all the elements of the Property. public Properties getAddressProp() { System.out.println(“Property Elements :” + addressProp); return addressProp; } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“applicationcontext.xml”); JavaCollection jc=(JavaCollection)context.getBean(“javaCollection”); jc.getAddressList(); jc.getAddressSet(); jc.getAddressProp(); } } Following is the configuration file applicationcontext.xml which has configuration for all the type of collections − <?xml version = “1.0” encoding = “UTF-8”?> <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”> <!– Definition for javaCollection –> <bean id = “javaCollection” class = “com.tutorialspoint.JavaCollection”> <!– results in a setAddressList(java.util.List) call –> <property name = “addressList”> <list> <value>INDIA</value> <value>JAPAN</value> <value>USA</value> <value>UK</value> </list> </property> <!– results in a setAddressSet(java.util.Set) call –> <property name = “addressSet”> <set> <value>INDIA</value> <value>JAPAN</value> <value>USA</value> <value>UK</value> </set> </property> <!– results in a setAddressProp(java.util.Properties) call –> <property name = “addressProp”> <props> <prop key = “one”>INDIA</prop> <prop key = “two”>JAPAN</prop> <prop key = “three”>USA</prop> <prop key = “four”>UK</prop> </props> </property> </bean> </beans> Output Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − List Elements :[INDIA, JAPAN, USA, UK] Set Elements :[INDIA, JAPAN, USA, UK] Property Elements :{four=UK, one=INDIA, two=JAPAN, three=USA} Print Page Previous Next Advertisements ”;

Spring DI – Constructor Based

Spring DI – Constructor-Based ”; Previous Next Constructor-Based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on the other class. Example The following example shows a class TextEditor that can only be dependency-injected with constructor injection. Let”s update the project created in Spring DI – Create Project chapter. We”re adding following files − TextEditor.java − A class containing a SpellChecker as dependency. SpellChecker.java − A dependency class. MainApp.java − Main application to run and test. Here is the content of TextEditor.java file − package com.tutorialspoint; public class TextEditor { private SpellChecker spellChecker; public TextEditor(SpellChecker spellChecker) { System.out.println(“Inside TextEditor constructor.” ); this.spellChecker = spellChecker; } public void spellCheck() { spellChecker.checkSpelling(); } } Following is the content of another dependent class file SpellChecker.java package com.tutorialspoint; public class SpellChecker { public SpellChecker(){ System.out.println(“Inside SpellChecker constructor.” ); } public void checkSpelling() { System.out.println(“Inside checkSpelling.” ); } } Following is the content of the MainApp.java file. package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“applicationcontext.xml”); TextEditor te = (TextEditor) context.getBean(“textEditor”); te.spellCheck(); } } Following is the configuration file applicationcontext.xml which has configuration for the constructor-based injection − <?xml version = “1.0” encoding = “UTF-8”?> <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”> <!– Definition for textEditor bean –> <bean id = “textEditor” class = “com.tutorialspoint.TextEditor”> <constructor-arg ref = “spellChecker”/> </bean> <!– Definition for spellChecker bean –> <bean id = “spellChecker” class = “com.tutorialspoint.SpellChecker”></bean> </beans> Output Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Inside SpellChecker constructor. Inside TextEditor constructor. Inside checkSpelling. Print Page Previous Next Advertisements ”;

Spring DI – Map Ref Constructor

Spring DI – Map Ref Constructor ”; Previous Next You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean. Now what if you want to pass Map. In this example, we”re showcasing passing direct values of the Map using constructor injection. Example The following example shows a class JavaCollection that is using collections as dependency injected using constructor arguments. Let”s update the project created in Spring DI – Create Project chapter. We”re adding following files − Address.java − A class to be used as dependency. JavaCollection.java − A class containing a collections of dependencies. MainApp.java − Main application to run and test. Here is the content of Address.java file − package com.tutorialspoint; public class Address { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return name; } } Here is the content of JavaCollection.java file − package com.tutorialspoint; import java.util.*; public class JavaCollection { Map<String, Address> addressMap; public JavaCollection() {} public JavaCollection(Map<String, Address> addressMap) { this.addressMap = addressMap; } // a setter method to set Map public void setAddressMap(Map<String, Address> addressMap) { this.addressMap = addressMap; } // prints and returns all the elements of the Map. public Map<String, Address> getAddressMap() { System.out.println(“Map Elements :” + addressMap); return addressMap; } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“applicationcontext.xml”); JavaCollection jc=(JavaCollection)context.getBean(“javaCollection”); jc.getAddressMap(); } } Following is the configuration file applicationcontext.xml which has configuration for all the type of collections − <?xml version = “1.0” encoding = “UTF-8”?> <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 = “address1” class = “com.tutorialspoint.Address”> <property name=”name” value=”INDIA”></property> </bean> <bean id = “address2” class = “com.tutorialspoint.Address”> <property name=”name” value=”JAPAN”></property> </bean> <bean id = “address3” class = “com.tutorialspoint.Address”> <property name=”name” value=”USA”></property> </bean> <bean id = “address4” class = “com.tutorialspoint.Address”> <property name=”name” value=”UK”></property> </bean> <bean id = “javaCollection” class = “com.tutorialspoint.JavaCollection”> <constructor-arg name = “addressMap”> <map> <entry key = “1” value-ref = “address1″/> <entry key = “2” value-ref = “address2″/> <entry key = “3” value-ref = “address3″/> <entry key = “4” value-ref = “address4″/> </map> </constructor-arg> </bean> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Map Elements :{1=INDIA, 2=JAPAN, 3=USA, 4=UK} Print Page Previous Next Advertisements ”;

Spring Boot CLI – Packaging Application

Spring Boot CLI – Packaging Application ”; Previous Next Spring boot CLI provides jar command in order to package a application as jar file. Let”s test the sample project created in Starter Thymeleaf Project Chapter to demonstrate the packaging capabilities of Spring CLI. Follow the below mentioned step to package the sample project. Package the application Type the following command E:/Test/TestApplication/> spring jar TestApplication.jar *.groovy Output Now you can see two new files created in TestApplication folder. TestApplication.jar − An executable jar file. TestApplication.jar.original − Original jar file. Include/Exclude By default following directories are included along with their contents. public resources static templates META-INF By default following directories are excluded along with their contents. repository build target *.jar files *.groovy files Using –include, we can include directories excluded otherwise. Using –exclude, we can exclude directories included otherwise. Running the Executable Jar Type the following command E:/Test/TestApplication/> java -jar TestApplication.jar You can see the following output on console. . ____ _ __ _ _ /\ / ___”_ __ _ _(_)_ __ __ _ ( ( )___ | ”_ | ”_| | ”_ / _` | \/ ___)| |_)| | | | | || (_| | ) ) ) ) ” |____| .__|_| |_|_| |___, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.6.3) 2022-02-03 11:47:42.298 INFO 8908 — [ main] .b.c.a.PackagedSpringApplicationLauncher : Starting PackagedSpringApplicationLauncher using Java 11.0.11 on DESKTOP-86KD9FC with PID 8908 (E:TestTestApplicationTestApplication.jar started by intel in E:TestTestApplication) 2022-02-03 11:47:42.310 INFO 8908 — [ main] .b.c.a.PackagedSpringApplicationLauncher : No active profile set, falling back to default profiles: default 2022-02-03 11:47:44.839 INFO 8908 — [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2022-02-03 11:47:44.863 INFO 8908 — [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2022-02-03 11:47:44.864 INFO 8908 — [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56] 2022-02-03 11:47:44.958 INFO 8908 — [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2022-02-03 11:47:44.959 INFO 8908 — [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1943 ms 2022-02-03 11:47:45.592 INFO 8908 — [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html] 2022-02-03 11:47:46.492 INFO 8908 — [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ”” 2022-02-03 11:47:46.514 INFO 8908 — [ main] .b.c.a.PackagedSpringApplicationLauncher : Started PackagedSpringApplicationLauncher in 5.295 seconds (JVM running for 6.089) Browse the application in Browser Our spring based rest application is now ready. Open url as “http://localhost:8080/” and you will see the following output. Go to Message Click on Message link and you will see the following output. Message: Welcome to TutorialsPoint.Com! Print Page Previous Next Advertisements ”;

Spring ORM – Maven Hibernate

Spring ORM – Maven Hibernate ”; Previous Next Let”s add following dependencies in pom.xml. Spring Framework Hibernate MySQL Connector Other related dependencies. Update the pom.xml as per below content. pom.xml <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>springorm</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Spring ORM</name> <description>Spring ORM Test Project</description> <properties> <org.springframework.version>4.3.7.RELEASE</org.springframework.version> <org.hibernate.version>5.2.9.Final</org.hibernate.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${org.hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${org.hibernate.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> <version>8.0.13</version> </dependency> <dependency> <groupId>com.sun.activation</groupId> <artifactId>javax.activation</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.1</version> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project> Now right click on the project name. Select Maven → Update Project to download the required dependencies. Print Page Previous Next Advertisements ”;

Spring ORM – Quick Guide

Spring ORM – Quick Guide ”; Previous Next Spring ORM – Overview The Spring Framework integrates well with ORM frameworks like Hibernate, Java Persistence API (JPA), Java Data Objects (JDO) and iBATIS SQL Maps. Spring provides resource management, data access object (DAO) implementations, and transaction strategies. Spring allows to configure ORM library features through dependency management. Spring maintains a uniform DAO Exception hiearchies and a generic transaction management for all the ORM libraries it supports. Spring IoC container facilitates ORM configurations and easy deployment. Following are the key benefits of using Spring framework to create ORM DAO. Easy to Test − Using spring IoC, an ORM implementation can be easily configured. Each piece of persistence unit can be tested in isolation. Common Data Access Exception − Spring wraps ORM Tools exceptions to a common runtime exception as DataAccessException. This approach helps to handle most persistence exception (non-recoverable) in appropriate layers. No need to handle ORM specific boilerplate catch/throws/exception declarations. General Resource Management − Spring application contexts manages persistence objects, their configurations easily. For example, Hibernate SessionFactory instances, JPA EntityManagerFactory instances, JDBC DataSource instances, iBatis SQL Maps configuration objects and other related objects. Spring handles the local as well JTA transaction management by itself. Integrated transaction management − Spring AOP can be used to wrap an ORM code with a declarative AOP styled interceptor either using @Transaction annotation or by specifying transaction AOP advice in XML configuration file. Spring handles transaction semantics, exception handling, rollback and so on. Spring allows to swap transaction managers without affecting the ORM code. Spring ORM – Environment Setup This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Maven and Eclipse on your machine before you set up Spring Framework − Setup Java Development Kit (JDK) You can download the latest version of SDK from Oracle”s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and have installed the JDK in C:jdk-11.0.11, you would have to put the following line in your C:autoexec.bat file. set PATH=C:jdk-11.0.11;%PATH% set JAVA_HOME=C:jdk-11.0.11 Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file. setenv PATH /usr/local/jdk-11.0.11/bin:$PATH setenv JAVA_HOME /usr/local/jdk-11.0.11 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE. Setup Eclipse IDE All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine. To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe %C:eclipseeclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display the following result − Install MySQL Database The most important thing you will need, of course is an actual running database with a table that you can query and modify. MySQL DB − MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation. In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier. Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:Program FilesMySQLmysql-connector-java-5.1.8. Accordingly, set CLASSPATH variable to C:Program FilesMySQLmysql-connector-java-5.1.8mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation. Set Database Credential When we install MySQL database, its administrator ID is set to root and it gives provision to set a password of your choice. Using root ID and password you can either create another user ID and password, or you can use root ID and password for your JDBC application. There are various database operations like database creation and deletion, which would need administrator ID and password. If you do not have sufficient privilege to create new users, then you can ask your Database Administrator (DBA) to create a user ID and password for you. Create Database To create the TUTORIALSPOINT database, use the following steps − Step 1 Open a Command Prompt and change to the installation directory as follows − C:> C:>cd Program FilesMySQLbin C:Program FilesMySQLbin> Note − The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server. Step 2 Start the database