Spring Boot JPA – Repository methods ”; Previous Next Let”s now analyze the methods available in repository interface which we”ve created. Repository – EmployeeRepository.java Following is the default code of Repository to implement CRUD operations on above entity, Employee. package com.tutorialspoint.repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.tutorialspoint.entity.Employee; @Repository public interface EmployeeRepository extends CrudRepository<Employee, Integer> { } Now this repository contains following methods by default. Sr.No Method & Description 1 count(): long returns the number of entities available. 2 delete(Employee entity): void deletes an entity. 3 deleteAll():void deletes all the entities. 4 deleteAll(Iterable< extends Employee > entities):void deletes the entities passed as argument. 5 deleteAll(Iterable< extends Integer > ids):void deletes the entities identified using their ids passed as argument. 6 existsById(Integer id):boolean checks if an entity exists using its id. 7 findAll():Iterable< Employee > returns all the entities. 8 findAllByIds(Iterable< Integer > ids):Iterable< Employee > returns all the entities identified using ids passed as argument. 9 findById(Integer id):Optional< Employee > returns an entity identified using id. 10 save(Employee entity): Employee saves an entity and return the updated one. 11 saveAll(Iterable< Employee> entities): Iterable< Employee> saves all entities passed and return the updated entities. Print Page Previous Next Advertisements ”;
Category: Java
Spring Boot CLI – Hello World Example ”; Previous Next In this example, we”ll create a Spring Boot + MVC + Rest based Web application. Step 1: Create source Folder Create a folder FirstApplication in E:Test folder. Step 2: Create Source File Create FirstApplication.groovy file in E:Test folder with following source code. @RestController class FirstApplication { @RequestMapping(“/”) String welcome() { “Welcome to TutorialsPoint.Com” } } Step 3: Run the application Type the following command E:/Test/> spring run FirstApplication.groovy Now Spring Boot CLI will come into action, download required dependencies, run the embedded tomcat, deploy the application and start it. You can see the following output on console. E:Test>spring run FirstApplication.groovy Resolving dependencies…………………………. . ____ _ __ _ _ /\ / ___”_ __ _ _(_)_ __ __ _ ( ( )___ | ”_ | ”_| | ”_ / _` | \/ ___)| |_)| | | | | || (_| | ) ) ) ) ” |____| .__|_| |_|_| |___, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.6.3) 2022-02-03 11:12:42.683 INFO 6956 — [ runner-0] o.s.boot.SpringApplication : Starting application using Java 11.0.11 on DESKTOP-86KD9FC with PID 6956 (started by intel in F:Test) 2022-02-03 11:12:42.710 INFO 6956 — [ runner-0] o.s.boot.SpringApplication : No active profile set, falling back to default profiles: default 2022-02-03 11:12:45.110 INFO 6956 — [ runner-0] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2022-02-03 11:12:45.138 INFO 6956 — [ runner-0] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2022-02-03 11:12:45.139 INFO 6956 — [ runner-0] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.56] 2022-02-03 11:12:45.229 INFO 6956 — [ runner-0] org.apache.catalina.loader.WebappLoader : Unknown class loader [org.springframework.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader@8646db9] of class [class org.springframework.boot.cli.compiler.ExtendedGroovyClassLoader$DefaultScopeParentClassLoader] 2022-02-03 11:12:45.333 INFO 6956 — [ runner-0] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2022-02-03 11:12:45.333 INFO 6956 — [ runner-0] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2124 ms 2022-02-03 11:12:46.901 INFO 6956 — [ runner-0] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ”” 2022-02-03 11:12:46.930 INFO 6956 — [ runner-0] o.s.boot.SpringApplication : Started application in 5.416 seconds (JVM running for 49.049) 2022-02-03 11:13:48.910 INFO 6956 — [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet ”dispatcherServlet” 2022-02-03 11:13:48.912 INFO 6956 — [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet ”dispatcherServlet” 2022-02-03 11:13:48.915 INFO 6956 — [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 3 ms Step 4: 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. Welcome to TutorialsPoint.Com Points to consider Following actions are taken by Spring CLI. All dependency JARs are downloaded for the first time only. Spring CLI automatically detects which dependency JARs are to be downloaded based on the classes and annotations used in code. Finally it compiles the code, deploy the war on a embedded tomcat, start embedded tomcat server on the default port 8080. Print Page Previous Next Advertisements ”;
“grab” Dependency Deduction ”; Previous Next Standard Groovy codebase contains a @Grab annotation so that dependencies on third-party libraries can be declared. Using @Grab annotation, Grape Dependency Manager downloads jar in similar fashion as that of Maven/Gradle without any build tool. Spring Boot attempts to deduce the required libraries based on code. For example, use of @RestController tells that “Tomcat” and “Spring MVC” libraries are to be grabbed. Grab Hints Following table details the hints that Spring Boot uses to download third party libraries − Sr.No. Hint & Dependency to Download/Link 1 JdbcTemplate, NamedParameterJdbcTemplate, DataSource JDBC Application 2 @EnableJms JMS Application 3 @EnableCaching Caching abstraction 4 @Test JUnit 5 @EnableRabbit RabbitMQ 6 @EnableReactor Project Reactor 7 extends Specification Spock test 8 @EnableBatchProcessing Spring Batch 9 @MessageEndpoint, @EnableIntegrationPatterns Spring Integration 10 @EnableDeviceResolver Spring Mobile 11 @Controller, @RestController, @EnableWebMvc Spring MVC + Embedded Tomcat 12 @EnableWebSecurity Spring Security 13 @EnableTransactionManagement Spring Transaction Management Print Page Previous Next Advertisements ”;
Spring Boot CLI – Home
Spring Boot CLI Tutorial PDF Version Quick Guide Resources Job Search Discussion Spring Boot CLI is a command line tool, which is used for a quick start with Spring. It allows running Groovy scripts. Groovy scripts are similar to Java code without any boilerplate code. Spring CLI helps to bootstrap a new project or write custom command for it. Audience This tutorial will be useful for most Java developers, starting from beginners to experts. After completing this tutorial, you will find yourself at a moderate level of expertise in Spring Boot CLI, from where you can take yourself to next levels. Prerequisites Knowledge of basic Java programming language and Spring Spring Tutorial is the only prerequisite for learning the concepts explained in this tutorial. Print Page Previous Next Advertisements ”;
Example – Spinners
Swing Examples – Spinners ”; Previous Next Learn how to play with Spinners in Swing UI programming. Here are most commonly used examples − How to create a spinner in Swing? Print Page Previous Next Advertisements ”;
Spring MVC – Generate RSS Feed Example ”; Previous Next The following example shows how to generate RSS Feed using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and then consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with the name TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes RSSMessage, RSSFeedViewer and RSSController under the com.tutorialspoint package. 3 Download the Rome library Rome and its dependencies rome-utils, jdom and slf4j from the same maven repository page. Put them in your CLASSPATH. 4 Create a properties file messages.properties under the SRC folder. 5 The final step is to create the content of the source and configuration files and export the application as explained below. RSSMessage.java package com.tutorialspoint; import java.util.Date; public class RSSMessage { String title; String url; String summary; Date createdDate; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } } RSSFeedViewer.java package com.tutorialspoint; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.view.feed.AbstractRssFeedView; import com.rometools.rome.feed.rss.Channel; import com.rometools.rome.feed.rss.Content; import com.rometools.rome.feed.rss.Item; public class RSSFeedViewer extends AbstractRssFeedView { @Override protected void buildFeedMetadata(Map<String, Object> model, Channel feed, HttpServletRequest request) { feed.setTitle(“TutorialsPoint Dot Com”); feed.setDescription(“Java Tutorials and Examples”); feed.setLink(“http://www.tutorialspoint.com”); super.buildFeedMetadata(model, feed, request); } @Override protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { List<RSSMessage> listContent = (List<RSSMessage>) model.get(“feedContent”); List<Item> items = new ArrayList<Item>(listContent.size()); for(RSSMessage tempContent : listContent ){ Item item = new Item(); Content content = new Content(); content.setValue(tempContent.getSummary()); item.setContent(content); item.setTitle(tempContent.getTitle()); item.setLink(tempContent.getUrl()); item.setPubDate(tempContent.getCreatedDate()); items.add(item); } return items; } } RSSController.java package com.tutorialspoint; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class RSSController { @RequestMapping(value=”/rssfeed”, method = RequestMethod.GET) public ModelAndView getFeedInRss() { List<RSSMessage> items = new ArrayList<RSSMessage>(); RSSMessage content = new RSSMessage(); content.setTitle(“Spring Tutorial”); content.setUrl(“http://www.tutorialspoint/spring”); content.setSummary(“Spring tutorial summary…”); content.setCreatedDate(new Date()); items.add(content); RSSMessage content2 = new RSSMessage(); content2.setTitle(“Spring MVC”); content2.setUrl(“http://www.tutorialspoint/springmvc”); content2.setSummary(“Spring MVC tutorial summary…”); content2.setCreatedDate(new Date()); items.add(content2); ModelAndView mav = new ModelAndView(); mav.setViewName(“rssViewer”); mav.addObject(“feedContent”, items); return mav; } } TestWeb-servlet.xml <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.BeanNameViewResolver” /> <bean id = “rssViewer” class = “com.tutorialspoint.RSSFeedViewer” /> </beans> Here, we have created a RSS feed POJO RSSMessage and a RSS Message Viewer, which extends the AbstractRssFeedView and overrides its method. In RSSController, we have generated a sample RSS Feed. 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 the TestWeb.war file in Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL − http://localhost:8080/TestWeb/rssfeed and we will see the following screen. Print Page Previous Next Advertisements ”;
Spring Batch – Basic Application ”; Previous Next This chapter shows you the basic Spring Batch application. It will simply execute a tasklet to displays a message. Our Spring Batch application contains the following files − Configuration file − This is an XML file where we define the Job and the steps of the job. (If the application involves readers and writers too, then the configuration of readers and writers is also included in this file.) Context.xml − In this file, we will define the beans like job repository, job launcher and transaction manager. Tasklet class − In this class, we will write the processing code job (In this case, it displays a simple message) Launcher class − in this class, we will launch the Batch Application by running the Job launcher. Create Project Create a new maven project as discussed in Spring Batch – Environment Chapter. pom.xml Following are the content of pom.xml file used in this maven project. <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 http://maven.apache.org/maven-v4_0_0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>SpringBatchSample</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>SpringBatchExample</name> <url>http://maven.apache.org</url> <properties> <jdk.version>21</jdk.version> <spring.version>5.3.14</spring.version> <spring.batch.version>4.3.4</spring.batch.version> <mysql.driver.version>5.1.25</mysql.driver.version> <junit.version>4.11</junit.version> </properties> <dependencies> <!– Spring Core –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <!– Spring jdbc, for database –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!– Spring XML to/back object –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <!– MySQL database driver –> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.driver.version}</version> </dependency> <!– Spring Batch dependencies –> <dependency> <groupId>org.springframework.batch</groupId> <artifactId>spring-batch-core</artifactId> <version>${spring.batch.version}</version> </dependency> <dependency> <groupId>org.springframework.batch</groupId> <artifactId>spring-batch-infrastructure</artifactId> <version>${spring.batch.version}</version> </dependency> <!– Spring Batch unit test –> <dependency> <groupId>org.springframework.batch</groupId> <artifactId>spring-batch-test</artifactId> <version>${spring.batch.version}</version> </dependency> <!– Junit –> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>spring-batch</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <downloadSources>true</downloadSources> <downloadJavadocs>false</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> </configuration> </plugin> </plugins> </build> </project> jobConfig.xml Following is the configuration file of our sample Spring Batch application. Create this file in src > main > resources folder of maven project. <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:batch = “http://www.springframework.org/schema/batch” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd “> <import resource=”context.xml” /> <!– Defining a bean –> <bean id = “tasklet” class = “MyTasklet” /> <!– Defining a job–> <batch:job id = “helloWorldJob”> <!– Defining a Step –> <batch:step id = “step1”> <tasklet ref = “tasklet”/> </batch:step> </batch:job> </beans> Context.xml Following is the context.xml of our Spring Batch application. Create this file in src > main > resources folder of maven project. <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.2.xsd”> <bean id = “jobRepository” class=”org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean”> <property name = “transactionManager” ref = “transactionManager” /> </bean> <bean id = “transactionManager” class = “org.springframework.batch.support.transaction.ResourcelessTransactionManager” /> <bean id = “jobLauncher” class = “org.springframework.batch.core.launch.support.SimpleJobLauncher”> <property name = “jobRepository” ref = “jobRepository” /> </bean> </beans> Tasklet.java Following is the Tasklet class which displays a simple message. Create this class in src > main > java folder of maven project. import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.repeat.RepeatStatus; public class MyTasklet implements Tasklet { @Override public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception { System.out.println(“Hello This is a sample example of spring batch”); return RepeatStatus.FINISHED; } } App.java Following is the code which launces the batch process. Create this class in src > main > java folder of maven project. import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args)throws Exception { String[] springConfig = {“jobConfig.xml”}; // Creating the application context object ApplicationContext context = new ClassPathXmlApplicationContext(springConfig); // Creating the job launcher JobLauncher jobLauncher = (JobLauncher) context.getBean(“jobLauncher”); // Creating the job Job job = (Job) context.getBean(“helloWorldJob”); // Executing the JOB JobExecution execution = jobLauncher.run(job, new JobParameters()); System.out.println(“Exit Status : ” + execution.getStatus()); } } Output Right click on the project in eclipse, select run as -> maven build . Set goals as clean package and run the project. You”ll see following output. [INFO] Scanning for projects… [INFO] [INFO] [1m—————-< [0;36mcom.tutorialspoint:SpringBatchSample[0;1m >—————-[m [INFO] [1mBuilding SpringBatchExample 1.0-SNAPSHOT[m [INFO] from pom.xml [INFO] [1m——————————–[ jar ]———————————[m [INFO] [INFO] [1m— [0;32mclean:3.2.0:clean[m [1m(default-clean)[m @ [36mSpringBatchSample[0;1m —[m [INFO] Deleting C:UsersTutorialspointeclipse-workspaceSpringBatchSampletarget [INFO] [INFO] [1m— [0;32mresources:3.3.1:resources[m [1m(default-resources)[m @ [36mSpringBatchSample[0;1m —[m [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 3 resources from srcmainresources to targetclasses [INFO] [INFO] [1m— [0;32mcompiler:2.3.2:compile[m [1m(default-compile)[m @ [36mSpringBatchSample[0;1m —[m [WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent! [INFO] Compiling 5 source files to C:UsersTutorialspointeclipse-workspaceSpringBatchSampletargetclasses [INFO] [INFO] [1m— [0;32mresources:3.3.1:testResources[m [1m(default-testResources)[m @ [36mSpringBatchSample[0;1m —[m [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 0 resource from srctestresources to targettest-classes [INFO] [INFO] [1m— [0;32mcompiler:2.3.2:testCompile[m [1m(default-testCompile)[m @ [36mSpringBatchSample[0;1m —[m [INFO] Nothing to compile – all classes are up to date [INFO] [INFO] [1m— [0;32msurefire:3.1.2:test[m [1m(default-test)[m @ [36mSpringBatchSample[0;1m —[m [INFO] [INFO] [1m— [0;32mjar:3.3.0:jar[m [1m(default-jar)[m @ [36mSpringBatchSample[0;1m —[m [INFO] Building jar: C:UsersTutorialspointeclipse-workspaceSpringBatchSampletargetspring-batch.jar [INFO] [1m————————————————————————[m [INFO] [1;32mBUILD SUCCESS[m [INFO] [1m————————————————————————[m [INFO] Total time: 4.426 s [INFO] Finished at: 2024-07-30T11:10:59+05:30 [INFO] [1m———————————————————————— To check the output of the above SpringBatch program, right click on App.java class and select run as -> Java application. It will produce the following output − Jul 30, 2024 11:21:25 AM org.springframework.batch.core.launch.support.SimpleJobLauncher afterPropertiesSet INFO: No TaskExecutor has been set, defaulting to synchronous executor. Jul 30, 2024 11:21:25 AM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run INFO: Job: [FlowJob: [name=helloWorldJob]] launched with the following parameters: [{}] Jul 30, 2024 11:21:25 AM org.springframework.batch.core.job.SimpleStepHandler handleStep INFO: Executing step: [step1] Hello This is a sample example of spring batch Jul 30, 2024 11:21:25 AM org.springframework.batch.core.step.AbstractStep execute INFO: Step: [step1] executed in 25ms Jul 30, 2024 11:21:25 AM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 47ms Exit Status : COMPLETED Print Page Previous Next Advertisements ”;
Spring ORM – Environment Setup ”; Previous Next 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 server by executing the following command, if it is already not running. C:Program FilesMySQLbin>mysqld C:Program FilesMySQLbin> Step 3 Create the TUTORIALSPOINT database by executing the following command − C:Program FilesMySQLbin> create database TUTORIALSPOINT; 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. For a complete understanding on MySQL database, study the MySQL Tutorial. Set Maven In this tutorial, we are using maven to run and build the spring based examples. Follow the Maven – Environment Setup to install maven. Print Page Previous Next Advertisements ”;
Spring SpEL – Useful Resources ”; Previous Next The following resources contain additional information on Spring SpEL. Please use them to get more in-depth knowledge on this topic. Useful Links on Spring SpEL SpEL −Spring Expression Language Documentation. 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. To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
Spring SpEL – Elvis Operator
Spring SpEL – Elvis Operator ”; Previous Next SpEL expression supports Elvis operator which is a short form of ternary operator. // Using ternary operator String result = name != null ? name: “unknown”; // Using Elvis Operator result = name?:”unknown”; Following example shows the various use cases. Example Let”s update the project created in Spring SpEL – Create Project chapter. We”re adding/updating following files − Employee.java − Employee class. MainApp.java − Main application to run and test. Here is the content of Employee.java file − package com.tutorialspoint; public class Employee { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } Here is the content of MainApp.java file − package com.tutorialspoint; import java.text.ParseException; import org.springframework.expression.EvaluationContext; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class MainApp { public static void main(String[] args) throws ParseException { ExpressionParser parser = new SpelExpressionParser(); Employee employee = new Employee(); EvaluationContext employeeContext = new StandardEvaluationContext(employee); // Evaluates to “unknown” String result = parser.parseExpression(“name?:”unknown””).getValue(employeeContext, String.class); System.out.println(result); employee.setName(“Mahesh”); // Evaluates to “Mahesh” result = parser.parseExpression(“name?:”unknown””).getValue(employeeContext, String.class); System.out.println(result); } } Output unknown Mahesh Print Page Previous Next Advertisements ”;