How to use external properties file in Spring boot

Using netbeans for typescript development

Configuring netbeans with Typescript plugin.


General steps taken in the video above.(Not the exact steps)

  1. Download typescript plugin for netbeans.
  1. Install the nbm file into Netbeans 8.1
  1. Download angular-2-beta-boilerplate project which I will be using for my typescript learning.
  1. Extract the downloaded angular-2-beta-boilerplate.zip. Rename the extracted directory to typescript-dev. Then open the package.json within the extracted directory and change the name property to typescript-dev.
  1. Using command prompt execute npm install on the director,y typescript-dev.
  1. Open the project in netbeans.
  1. Open command prompt on typescript-dev directory and execute npm run gulp. Keep this running as long as you are working on the project.
  1. Open another command prompt on typescript-dev directory and execute npm start. Keep this running as long as you are working on the project.
  1. The project is ready on url http://localhost:3000/. The port number could be different in your machine
  1. Now the project is ready for development in Netbeans 8.1

My first typescript.

My first typescript with Netbeans.

General steps taken in the video above.(Not the exact steps)

  1. Create directory called 01 on the existing directory dev. Then add file abc.html and file ts1.ts in that directory. See example below:
  2. typescript-dev-dir

  1. Include ts1.js file into the abc.html file.
  1. Add div tag with id=”content” in the body tag of the abc.html. After changing the the abc.html the file will look something like the below:

  2. Smiley face

  1. Replace the content of ts1.ts with the below:
class MyStarterTypeScriptTemplate {
    element: HTMLElement;
    span1: HTMLElement;
    paragraph1: HTMLParagraphElement;

    constructor(element: HTMLElement) {
        // 1. define the main element
        this.element = element;

        // example of directly assigning value into html page.
        this.element.innerHTML += "<h1>Meaningless text in header 1: </h1>";

        // 2. define a sub elements
        this.span1 = document.createElement('span');
        this.paragraph1 = document.createElement('p');

        // 3. Change the content of the sub elements.
        this.span1.innerHTML = 'Text displayed into span!';
        this.paragraph1.innerHTML = 'Text displayed into paragraph!';

        // 4. attach the sub element to the main element.
        this.element.appendChild(this.span1);
        this.element.appendChild(this.paragraph1);
    }

    /**
     * A simple method!
     */
    toString() {
        return 'Hello';
    }
}

window.onload = () => {

    // defining a el variable with the element from the html page
    let el: HTMLElement = document.getElementById('content');

    // Initializing class
    let myTemplate = new MyStarterTypeScriptTemplate(el);

    // Calling method of the object myTemplate
    let toStringValue = myTemplate.toString();

    // displaying some values to different output options.
    console.log("[console] "+toStringValue);
    window.alert("[alert] "+toStringValue);
};
  1. The new changes can be checked on url http://localhost:3000/dev/01/abc.html. The port number could be different in your machine

 

NOTE
The sample maven project used for this exercise can be downloaded from:typescript-dev

Reference:

  1. angular-2-beta-boilerplate
  2. typescript-editor

My first Typescript project with Visual Studio Community 2015

Upper case table names in Mysql which comes with xampp



Below are the general steps taken in the video above.(Not the exact steps)

Check the default variable value in Mysql first.

  1. Open xampp control panel. Start mysql.
  1. Open Shell from xampp control panel.
  1. Login to mysql database.
  1. Execute the below command to get the default value from mysql server.
  2. show variables where variable_name = "lower_case_table_names";
    The above will return a result similar to below:
    +------------------------+-------+
    | Variable_name          | Value |
    +------------------------+-------+
    | lower_case_table_names | 1     |
    +------------------------+-------+
    1 row in set (0.37 sec)
  1. In order to make the table names upper case, we need to change the value of variable lower_case_table_names from 1 to 2.

Change variable value.

  1. Open my.ini from xampp control panel.
  1. Find for [mysqld] text in the file.
  1. Add the text below on next line after text [mysqld] and save the file.
  2. lower_case_table_names=2
    After applying the changes above, the portion of configuration will look similar like below:
    # The MySQL server
    [mysqld]
    lower_case_table_names=2
  1. Restart mysql from xampp control panel.

Try creating table with Upper case name.

Below are the sequence of sql used to create database and table:

    create database case1;
    use case1;
    create table Mapple(idOne varchar(1));
    show tables;
    show columns from Mapple;
    select * from mapple;
    drop database case1;
    Reference or sites showed in the video:

  1. change-table-name-to-upper-case

Maven liquibase skeleton project

Part 1 and Part 2 in a playlist


General steps taken in the video above.(Not the exact steps)

  1. Start mysql and create database sample_one.
  1. Create new maven java application. I named it maven_liquibase_skeleton.
  1. Add mysql and liquibase dependency to pom.xml file. (The below was taken from Maven liquibase configuration with some my own changes)
  2. <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
    </dependencies>
  1. Add liquibase plugin to pom.xml file. (The below was taken from Maven liquibase configuration with some my own changes)
  2. <build>
    	<plugins>
    		<plugin>
    			<groupId>org.liquibase</groupId>
    			<artifactId>liquibase-maven-plugin</artifactId>
    			<version>3.5.0</version>
    			<configuration>                  
    				<propertyFile>src/main/resources/liquibase/sample_one_database_config.properties</propertyFile>
    				<logging>debug</logging>
    				<dropFirst>true</dropFirst>
    			</configuration>                
    			<executions>
    				<execution>
    					<phase>process-resources</phase>                                                                  
    					<goals>
    						<goal>update</goal>
    					</goals>
    				</execution>
    			</executions>
    		</plugin> 	
    	</plugins>
    </build>
  1. Create sample_one_database_config.properties on directory, {project_source_directory}/src/main/resources/liquibase.
  1. Add the below content into the file sample_one_database_config.properties in path .
  2. driver: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/sample_one
    username: greenhorn
    password: greenhorn
    changeLogFile: src/main/resources/liquibase/sample_one_database.changelog.xml
  1. Create the changeLogFile file as mentioned in the above content. Create sample_one_database.changelog.xml on directory, {project_source_directory}/src/main/resources/liquibase.
  1. Add the below content into the file sample_one_database.changelog.xml.(The below was taken from Liquibase home page with some my own changes)
  2. <?xml version="1.0" encoding="UTF-8"?>
    
    <databaseChangeLog
            xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
            xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd
            http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
    
        <preConditions>
            <runningAs username="liquibase"/>
        </preConditions>
    
        <changeSet id="1" author="nvoxland">
            <createTable tableName="person">
                <column name="id" type="int" autoIncrement="true">
                    <constraints primaryKey="true" nullable="false"/>
                </column>
                <column name="firstname" type="varchar(50)"/>
                <column name="lastname" type="varchar(50)">
                    <constraints nullable="false"/>
                </column>
                <column name="state" type="char(2)"/>
            </createTable>
        </changeSet>
    
        <changeSet id="2" author="nvoxland">
            <addColumn tableName="person">
                <column name="username" type="varchar(8)"/>
            </addColumn>
        </changeSet>
        <changeSet id="3" author="nvoxland">
            <addLookupTable
                existingTableName="person" existingColumnName="state"
                newTableName="state" newColumnName="id" newColumnDataType="char(2)"/>
        </changeSet>
    
        <!--external files-->
        <include file="src/main/resources/liquibase/sample_one_database.default-data.xml"/>
    
    </databaseChangeLog>
  1. Create the file mentioned by the <include file> tag in the above content. Create sample_one_database.default-data.xml on directory, {project_source_directory}/src/main/resources/liquibase.
  1. Add the below content into the file sample_one_database.default-data.xml.
  2. <?xml version="1.0" encoding="UTF-8"?>
    <databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd
        http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
        
        <changeSet id="1" author="bob">
            <createTable tableName="ResetPassword">
                <column name="Username" type="varchar(30)">
                    <constraints primaryKey="true" nullable="false"/>
                </column>
                <column name="Email" type="varchar(150)">
                    <constraints nullable="false"/>
                </column>
                <column name="active" type="boolean" defaultValueBoolean="true"/>
            </createTable>
        </changeSet>
    </databaseChangeLog>
  1. Clean and Build the project from Netbeans.


NOTE
The sample maven project used for this exercise can be downloaded from:

maven_liquibase_skeleton

    Reference or sites showed in the video:

  1. http://www.liquibase.org/
  2. Maven liquibase configuration
  3. Maven update plugin

Spring MVC with form binding

Part 1

Part 2

General steps taken in the video above.(Not the exact steps)

  1. Create new maven java web application.
  1. Add spring dependency to pom.xml file
  2. <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-webmvc</artifactId>
    	<version>4.2.5.RELEASE</version>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-core</artifactId>
    	<version>4.2.5.RELEASE</version>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-beans</artifactId>
    	<version>4.2.5.RELEASE</version>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-context</artifactId>
    	<version>4.2.5.RELEASE</version>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-web</artifactId>
    	<version>4.2.5.RELEASE</version>
    </dependency>
    
  1. Create web.xml.
  1. Add page userForm.jsp to WEB-INF/pages/
  2. <%@ page contentType="text/html; charset=ISO-8859-1" %>
    <%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc" %>
    <html>
    	<head>
    		<title>Spring MVC Form Handling</title>
    	</head>
    	<body>
    		<h2>User Registration Form</h2>
    		<mvc:form modelAttribute="user" action="result.mvc">
    			<table>
    				<tr>
    					<td><mvc:label path="name">Name</mvc:label></td>
    					<td><mvc:input path="name" /></td>
    				</tr>
    				<tr>
    					<td><mvc:label path="lastname">Last Name</mvc:label></td>
    					<td><mvc:input path="lastname" /></td>
    				</tr>
    				<tr>
    					<td><mvc:label path="password">Password</mvc:label></td>
    					<td><mvc:password path="password" /></td>
    				</tr>
    				<tr>
    					<td><mvc:label path="detail">Detail</mvc:label></td>
    					<td><mvc:textarea path="detail" /></td>
    				</tr>
    				<tr>
    					<td><mvc:label path="birthDate">Birth Date</mvc:label></td>
    					<td><mvc:input path="birthDate" /></td>
    				</tr>
    				<tr>
    					<td><mvc:label path="gender">Gender</mvc:label></td>
    					<td><mvc:radiobuttons path="gender" items="${genders}" /></td>
    				</tr>
    				<tr>
    					<td><mvc:label path="country">Country</mvc:label></td>
    					<td><mvc:select path="country" items="${countries}" /></td>
    				</tr>
    				<tr>
    					<td><mvc:label path="nonSmoking">Non Smoking</mvc:label></td>
    					<td><mvc:checkbox path="nonSmoking" /></td>
    				</tr>
    				<tr>
    					<td colspan="2">
    						<input type="submit" value="Submit" />
    					</td>
    				</tr>
    			</table>
    		</mvc:form>
    	</body>
    </html>
    
  1. Add page userResult.jsp to WEB-INF/pages/
  2. <%@ page contentType="text/html; charset=ISO-8859-1" %>
    <%@taglib uri="http://www.springframework.org/tags/form" prefix="mvc" %>
    <html>
    	<head>
    		<title>Spring MVC Form Handling</title>
    	</head>
    	<body>
    		<h2>User Registration Result</h2>
    		<table>
    			<tr>
    				<td>Name</td>
    				<td>${u.name}</td>
    			</tr>
    			<tr>
    				<td>Last name</td>
    				<td>${u.lastname}</td>
    			</tr>
    			<tr>
    				<td>Password</td>
    				<td>${u.password}</td>
    			</tr>
    			<tr>
    				<td>Detail</td>
    				<td>${u.detail}</td>
    			</tr>
    			<tr>
    				<td>Birth Date</td>
    				<td>${u.birthDate}</td>
    			</tr>
    			<tr>
    				<td>Gender</td>
    				<td>${u.gender}</td>
    			</tr>
    			<tr>
    				<td>Country</td>
    				<td>${u.country}</td>
    			</tr>
    			<tr>
    				<td>Non-Smoking</td>
    				<td>${u.nonSmoking}</td>
    			</tr>
    		</table>
    	</body>
    </html>
    
  1. Create modal class User in package org.greenhorn.entity
  2. 
    import java.time.LocalDate;
    import org.springframework.format.annotation.DateTimeFormat;
    
    public class User {
    
    	private String name;
    	private String lastname;
    	private String password;
    	private String detail;
    	@DateTimeFormat(pattern = "yyyy-MM-dd")
    	private LocalDate birthDate;
    	private Gender gender;
    	private String country;
    	private boolean nonSmoking;
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public String getLastname() {
    		return lastname;
    	}
    
    	public void setLastname(String lastname) {
    		this.lastname = lastname;
    	}
    
    	public String getPassword() {
    		return password;
    	}
    
    	public void setPassword(String password) {
    		this.password = password;
    	}
    
    	public String getDetail() {
    		return detail;
    	}
    
    	public void setDetail(String detail) {
    		this.detail = detail;
    	}
    
    	public LocalDate getBirthDate() {
    		return birthDate;
    	}
    
    	public void setBirthDate(LocalDate birthDate) {
    		this.birthDate = birthDate;
    	}
    
    	public Gender getGender() {
    		return gender;
    	}
    
    	public void setGender(Gender gender) {
    		this.gender = gender;
    	}
    
    	public String getCountry() {
    		return country;
    	}
    
    	public void setCountry(String country) {
    		this.country = country;
    	}
    
    	public boolean isNonSmoking() {
    		return nonSmoking;
    	}
    
    	public void setNonSmoking(boolean nonSmoking) {
    		this.nonSmoking = nonSmoking;
    	}
    }
    
  1. Create modal class Gender in package org.greenhorn.entity
  2. public enum Gender {
    	MALE,
    	FEMALE;
    }
    
  1. Create controller class UserController to manage request in package org.greenhorn.controller
  2. import org.greenhorn.entity.Gender;
    import org.greenhorn.entity.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;
    
    @Controller
    public class UserController {
    
    	private static final String[] countries = {"Turkey",
    		"United States", "Germany"};
    
    	@RequestMapping(value = "/form")
    	public ModelAndView user() {
    
    		User user = new User();
    		user.setLastname("Macau");
    
    		ModelAndView modelAndView
    				= new ModelAndView("userForm", "user", user);
    		modelAndView.addObject("genders", Gender.values());
    		modelAndView.addObject("countries", countries);
    		return modelAndView;
    	}
    
    	@RequestMapping(value = "/result")
    	public ModelAndView processUser(User user) {
    		ModelAndView modelAndView = new ModelAndView();
    		modelAndView.setViewName("userResult");
    		modelAndView.addObject("u", user);
    		return modelAndView;
    	}
    }
    
  1. Create class AppConfig to manage request in package org.greenhorn.spring.configwith the below content:
  2. import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    
    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = {"org.greenhorn.controller"})
    public class AppConfig {
    
    	@Bean
    	public InternalResourceViewResolver getInternalResourceViewResolver() {
    		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    		resolver.setPrefix("/WEB-INF/pages/");
    		resolver.setSuffix(".jsp");
    		return resolver;
    	}
    }
    
  1. Update web.xml with the spring configuration class, AppConfig, DispatcherServlet.
  2. <servlet>
    	<servlet-name>springmvc</servlet-name>
    	<servlet-class>
    		org.springframework.web.servlet.DispatcherServlet
    	</servlet-class>
    	
    	<init-param>
    		<param-name>contextClass</param-name>
    		<param-value>
    			org.springframework.web.context.support.AnnotationConfigWebApplicationContext
    		</param-value>
    	</init-param>
    	
    	<init-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>
    			org.greenhorn.spring.config.AppConfig
    		</param-value>
    	</init-param>
    	
    	<load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
    	<servlet-name>springmvc</servlet-name>
    	<url-pattern>*.mvc</url-pattern>
    </servlet-mapping>
    
  1. Run the project from netbeans.


NOTE
The sample maven project used for this exercise can be downloaded from:

spring-mvc-3

    Reference:

  1. Beginning Spring

Simple Spring MVC Application (Annotation)



General steps taken in the video above.(Not the exact steps)

  1. Clone project from previous blog post: Simple Spring MVC Application. Rename the project to spring-mvc-2
  1. Create AppConfig.java class in package org.greenhorn.spring.config with the below content:
  2. import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    
    @Configuration
    @ComponentScan(basePackages = {"org.greenhorn"})
    public class AppConfig {
    
    	@Bean
    	public InternalResourceViewResolver getInternalResourceViewResolver() {
    		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    		resolver.setPrefix("/WEB-INF/pages/");
    		resolver.setSuffix(".jsp");
    		return resolver;
    	}
    }
    
  1. Delete springmvc-servlet.xml. This has been replaced by AppConfig.java class:
  1. Update web.xml with the spring configuration class, AppConfig:
  2. <init-param>
    	<param-name>contextClass</param-name>
    	<param-value>
    		org.springframework.web.context.support.AnnotationConfigWebApplicationContext
    	</param-value>
    </init-param>
    
    <init-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>
    		org.greenhorn.spring.config.AppConfig
    	</param-value>
    </init-param>
    
    
  1. Change HelloReaderController.java. Change RequestMapping to “/hi” and change the “message
  1. Run the project from netbeans.


NOTE
The sample maven project used for this exercise can be downloaded from:

spring-mvc-2

Simple Spring MVC Application



General steps taken in the video above.(Not the exact steps)

  1. Create new maven java web application.
  1. Add spring dependency to pom.xml file:
  2. <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-webmvc</artifactId>
    	<version>4.2.5.RELEASE</version>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-core</artifactId>
    	<version>4.2.5.RELEASE</version>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-beans</artifactId>
    	<version>4.2.5.RELEASE</version>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-context</artifactId>
    	<version>4.2.5.RELEASE</version>
    </dependency>
    
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-web</artifactId>
    	<version>4.2.5.RELEASE</version>
    </dependency>
    
  1. Create web.xml.
  1. Define the Dispatcher Servlet in the web.xml
  2. <servlet>
    	<servlet-name>springmvc</servlet-name>
    	<servlet-class>
    		org.springframework.web.servlet.DispatcherServlet
    	</servlet-class>
    	<load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
    	<servlet-name>springmvc</servlet-name>
    	<url-pattern>*.mvc</url-pattern>
    </servlet-mapping>
    
  1. Create the application context configuration(springmvc-servlet.xml). Select “context” during creation wizard steps. :
  2. <context:component-scan base-package="org.greenhorn" />
    
    <context:annotation-config />
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	<property name="prefix" value="/WEB-INF/pages/" />
    	<property name="suffix" value=".jsp" />
    </bean>
    
  1. Create simple controller HelloReaderController.java in package org.greenhorn:
  2. import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;
    
    @Controller
    public class HelloReaderController {
    
    	@RequestMapping(value = "/hello")
    	public ModelAndView sayHello() {
    		ModelAndView mv = new ModelAndView();
    		mv.addObject("message", "Hello Reader!");
    		mv.setViewName("helloReader");
    		return mv;
    	}
    }
    
  1. Create the JSP file named helloReader.jsp under the /WEB-INF/pages/ folder:
  2. <html>
    	<body>
    		${message}
    	</body>
    </html>
    
    
  1. Run the project from netbeans.


NOTE
The sample maven project used for this exercise can be downloaded from:

spring-mvc-1

DAO on Plain JPA

Part 1

Part 2

General steps taken in the video above.(Not the exact steps)

  1. Create Dao interface in package org.entity.dao with below definition:
  2. public interface Dao {
    	public boolean insert(T t);
    	public boolean update(T t);
    	public boolean delete(T t);
    }
    

  1. Create StudentDaoJpaImpl class in package org.entity.dao.impl with the below content:
  2. /**
     * @PersistenceUnit has a unitName attribute. Its value is optional;
     * however, it can be used to inject another entityManagerFactory bean
     * defined in the container.
     */
    @PersistenceUnit
    private EntityManagerFactory entityManagerFactory;
    
    @Override
    public boolean insert(Student t) {
    	EntityManager entityManager = entityManagerFactory
    			.createEntityManager();
    	EntityTransaction transaction = entityManager.getTransaction();
    	transaction.begin();
    
    	entityManager.persist(t);
    
    	transaction.commit();
    	entityManager.close();
    
    	return true;
    }
    

  1. Added StudentDaoJpaImpl as spring managed bean in DBConfiguration class:
  2. @Bean
    public StudentDaoJpaImpl studentDao() {
    	StudentDaoJpaImpl dao = new StudentDaoJpaImpl();
    	return dao;
    }
    

  1. Change main method to use the spring managed bean to persist Student object:
  2. 	
    public static void main(String[] args) {
    	ApplicationContext applicationContext = new AnnotationConfigApplicationContext(
    			DBConfiguration.class);
    	StudentDaoJpaImpl dao = applicationContext.getBean(StudentDaoJpaImpl.class);
    	Student student = new Student();
    	student.setFirstName("Grey");
    	student.setLastName("Joy");
    	dao.insert(student);
    }
    

  1. Run main method.


NOTE
The sample maven project used for this exercise can be downloaded from:

jpa_spring_2

Spring + JPA + Hibernate + mysql in Netbeans 8.1

Part 1

Part 2

General steps taken in the video above.(Not the exact steps)

  1. Add spring framework dependencies as below into the pom.xml:
  2. <!-- spring framework -->
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-orm</artifactId>
    	<version>4.0.5.RELEASE</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-context</artifactId>
    	<version>4.0.5.RELEASE</version>
    </dependency>
    

  1. Moved class Student and Book into package org.entity. Just to keep separation clear.

  1. Add class DBConfiguration into package org.entity.config. Below is the class content:
  2. import java.util.HashMap;
    import java.util.Map;
    import org.springframework.context.annotation.Bean;
    import org.springframework.jdbc.datasource.DriverManagerDataSource;
    import javax.sql.DataSource;
    import org.hibernate.jpa.HibernatePersistenceProvider;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
    
    @Configuration
    public class DBConfiguration {
    
        @Bean
        public DataSource dataSource() {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://localhost:3306/jpa_2");
            dataSource.setUsername("greenhorn");
            dataSource.setPassword("greenhorn");
            return dataSource;
        }
    
        private Map jpaProperties() {
            Map jpaPropertiesMap = new HashMap();
            jpaPropertiesMap.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
            jpaPropertiesMap.put("hibernate.hbm2ddl.auto", "create");
            return jpaPropertiesMap;
        }
    
        @Bean
        public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
            LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
            factoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
            factoryBean.setDataSource(dataSource());
            factoryBean.setPackagesToScan("org.entity");
            factoryBean.setJpaPropertyMap(jpaProperties());
            return factoryBean;
        }
    
    }
    

  1. Change Main class as below:
  2. import org.entity.Student;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.EntityTransaction;
    import org.entity.config.DBConfiguration;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class Main {
    
        public static void main(String[] args) {
            ApplicationContext applicationContext
                    = new AnnotationConfigApplicationContext(DBConfiguration.class);
            EntityManagerFactory entityManagerFactory
                    = applicationContext.getBean(EntityManagerFactory.class);
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            EntityTransaction transaction = entityManager.getTransaction();
            transaction.begin();
            Student student = new Student();
            student.setFirstName("Jambu");
            student.setLastName("Jack");
            entityManager.persist(student);
            transaction.commit();
            entityManager.close();
        }
    }
    

  1. Delete META-INF directory with its content, persistence.xml.

  1. Run Main class from Netbeans 8.1


NOTE
The sample maven project used for this exercise can be downloaded from

jpa1_spring