Mini Spring Boot Web Application

After a couple of years of reading about Spring Boot and never having actually tried it out, I thought now was the time to build a little example to find out how easy it is and also because I need a simple app for my E.L.K. project (more on that later!).

There’s a very good intro to get people off the ground from Spring on their website https://spring.io/guides/gs/spring-boot/ which I read through and then tweaked.

The source code for the rest of this blog article can be found here https://github.com/vls29/spring-boot-example.

For the web application I’ve used Maven, but instead of following the guide exactly as the guide extended the spring boot starter parent pom, I decided to find out what I might need to get the project to run by using only the poms/jars that I thought would be essential.

As such the pom doesn’t have a parent and references only the relevant spring boot related poms and jars:

  • spring-boot-starter-actuator to bring in the “…production grade services…” and see what they do!
  • spring-boot-starter-web to bring in all the Spring MVC and embedded tomcat goodies
  • and spring-boot-starter-log4j2 to add in logging which I’m going to need for the E.L.K. project

There’s also two plugins, the maven compiler plugin to make sure it compiles at Java version 8 and the spring-boot-maven-plugin as the guide mentioned that it bundles the jar with the included maven dependencies (note if you’re not extending the spring boot super pom, you’ll need an execution goal for the spring-boot-maven-plugin otherwise nothing will happen).

The Application and HelloWorldController are based around the example from the getting started guide, but the UserController is one I’ve added.  It has a noddy example service which receives a path variable long representing the id of the user to retrieve (although in the example it doesn’t matter what value!).  It constructs a static user and returns the user object to the consumer.  Spring MVC then uses Jackson to marshal the object to JSON.

The final file is then a Run Config for Eclipse which executes the “spring-boot:run” goal and starts up the app from Eclipse.

The result is a very simple service that can retrieve our fake user as shown in the image below.

spring-boot-example-1

I was pleasently surprised how quick it was to create a service and all the documentation available to set it up.

That’s it for now, but there will be more on E.L.K. soon!

Example of a Spring 3.2 and Hibernate 4 repository base

The is a partial example of a spring 3.2 and hibernate 4 project repository base layer. It doesn’t necessarily compile or even do anything, but it’s an example…

aCtx-repository.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
					    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
					    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="packagesToScan" value="uk.co.vsf.penny.domain.impl" />
		<property name="dataSource" ref="dataSource" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
				<prop key="hibernate.hbm2ddl.auto">create</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

	<context:property-placeholder location="jdbc.properties" />

	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<tx:annotation-driven transaction-manager="transactionManager"
		proxy-target-class="true" />

</beans>

aCtx-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="baseDao" class="uk.co.vsf.penny.repository.dao.impl.BaseDao">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<bean id="accountDao"
		  class="uk.co.vsf.penny.repository.dao.impl.AccountDaoImpl"
		  parent="baseDao">
	</bean>

	<bean id="transactionDao"
		  class="uk.co.vsf.penny.repository.dao.impl.TransactionDaoImpl"
		  parent="baseDao">
	</bean>

</beans>

aCtx-base.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
					    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<context:component-scan base-package="uk.co.vsf.penny" />
</beans>

BaseDao.java

public class BaseDao {

    private SessionFactory sessionFactory;

    protected SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Long totalTableCount(Class<?> clazz) {
        Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(clazz);
        criteria.setProjection(Projections.rowCount());
        return (Long) criteria.uniqueResult();
    }
}

AccountDaoImpl.java

public class AccountDaoImpl extends BaseDao implements AccountDao {

    public void addAccount(Account account) {
        getSessionFactory().getCurrentSession().save(account);
    }

    public void updateAccount(Account account) {
        getSessionFactory().getCurrentSession().update(account);
    }

    public void deleteAccount(Account account) {
        getSessionFactory().getCurrentSession().delete(account);
    }

    @Override
    public Long countAccountsForUser(User user) {
        Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Account.class);
        criteria.add(Restrictions.eq("user", user));
        criteria.setProjection(Projections.rowCount());
        return (Long) criteria.uniqueResult();
    }
}

Account.java

@Entity
@Table
public class Account {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(nullable = false)
    private String name;
    @Column(nullable = true)
    private String extraInfo;
    @Column(nullable = true)
    private Money startingBalance;

    @Column(nullable = true)
    @Temporal(TemporalType.DATE)
    private Calendar statementDate;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "account", orphanRemoval = true)
    private List<Transaction> transactions;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, optional = false)
    private User user;
}

Spring MVC 3.0.5 with Hibernate and Maven project

I’ve just started trying to piece together a Spring MVC project with Hibernate and Maven in Eclipse. So far it has been VERY frustrating as Eclipse wasn’t publishing the app with the lib files. That took over an hour of my time up and I haven’t yet managed to get it to run. I will update the following when I finally get it working, but here are the basics of what I have so far Ok, I’ve got it working finally. Turns out there are some unusual settings files that contain relevant paths for web app deployment. The following have been updated and should work:

MyObject.java

package uk.co.vsf.MyApp.database.beans;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class MyObject
{
	@Id
	private Integer myId;

	public MyObject(Integer myId)
	{
		this.myId = myId;
	}

	public void setMyId(Integer myId)
	{
		this.myId = myId;
	}

	public Integer getMyId()
	{
		return myId;
	}
}

Continue reading “Spring MVC 3.0.5 with Hibernate and Maven project”