org.hibernate.LazyInitializationException could not initialize proxy – no Session

Error LazyInitializationException 🙂

Bismillah

q> Ini coding header


package com.saifiahmada.spring.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.GenericGenerator;

@Entity
public class HdrTest implements Serializable {

private static final long serialVersionUID = 1L;

@Id @GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "HDR_ID" , length=36)
private String hdrId;

@Temporal(TemporalType.TIMESTAMP)
private Date tglTest;

@Column(length = 20)
private String username;

@OneToMany(cascade={CascadeType.ALL})
@JoinColumn(name="hdr_id")
private List<DtlTest> dtlTests;

public String getHdrId() {
return hdrId;
}

public void setHdrId(String hdrId) {
this.hdrId = hdrId;
}

public Date getTglTest() {
return tglTest;
}

public void setTglTest(Date tglTest) {
this.tglTest = tglTest;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public List<DtlTest> getDtlTests() {
return dtlTests;
}

public void setDtlTests(List<DtlTest> dtlTests) {
this.dtlTests = dtlTests;
}
}

q> Ini coding detail


package com.saifiahmada.spring.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import org.hibernate.annotations.GenericGenerator;

@Entity
public class DtlTest implements Serializable {

private static final long serialVersionUID = 1L;

@Id @GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "DTL_ID" , length=36)
private String dtlId;

@Column(name="ID_SOAL", length=36)
private String idSoal;

@Column(length=1)
private String jawabanSiswa;

@ManyToOne
@JoinColumn(name="hdr_id")
private HdrTest hdrTest;

public DtlTest() {

}

public String getDtlId() {
return dtlId;
}

public void setDtlId(String dtlId) {
this.dtlId = dtlId;
}

public String getIdSoal() {
return idSoal;
}

public void setIdSoal(String idSoal) {
this.idSoal = idSoal;
}

public String getJawabanSiswa() {
return jawabanSiswa;
}

public void setJawabanSiswa(String jawabanSiswa) {
this.jawabanSiswa = jawabanSiswa;
}

public HdrTest getHdrTest() {
return hdrTest;
}

public void setHdrTest(HdrTest hdrTest) {
this.hdrTest = hdrTest;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dtlId == null) ? 0 : dtlId.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DtlTest other = (DtlTest) obj;
if (dtlId == null) {
if (other.dtlId != null)
return false;
} else if (!dtlId.equals(other.dtlId))
return false;
return true;
}

@Override
public String toString() {
return "DtlTest [dtlId=" + dtlId + "]";
}

}

q> Ketika coba mengambil data dengan coding ini


package com.saifiahmada.spring;

import java.util.List;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;

import com.saifiahmada.spring.domain.DtlTest;
import com.saifiahmada.spring.domain.HdrTest;
import com.saifiahmada.spring.repository.HdrTestRepository;

@Configurable
@EnableAutoConfiguration
public class OfflineTest {

public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(OfflineTest.class, args);

HdrTestRepository repo = (HdrTestRepository) ctx.getBean("hdrTestRepository");

List<HdrTest> list = repo.findAll();
for (HdrTest hdr : list) {
System.out.println("" + hdr.getHdrId());
System.out.println("" + hdr.getUsername());
System.out.println("" + hdr.getTglTest());
for (DtlTest dtl : hdr.getDtlTests()) {
System.out.println("" + dtl.getDtlId());
System.out.println("" + dtl.getIdSoal());
System.out.println("" + dtl.getJawabanSiswa());
}
}

}
}

q> Muncul error ini

Exception in thread “main” org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.saifiahmada.spring.domain.HdrTest.dtlTests, could not initialize proxy – no Session

q> Coba kita tambahkan code ini pada header

@OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.EAGER)

q> Sehingga coding untuk OneToMany pada header seperti ini :

@OneToMany(cascade={CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinColumn(name="hdr_id")
private List<DtlTest> dtlTests;

q> Berhasil mengambil seluruh header beserta detailnya 🙂

Alhamdulillah

Advertisements

melihat bean yang diload pada spring boot

bean apa saja yang diload ketika spring boot dijalankan

Bismillah


package com.saifiahmada.spring;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;

@Configurable
@EnableAutoConfiguration
public class OfflineTest {

public static void main(String [] args){
ApplicationContext ctx = SpringApplication.run(OfflineTest.class, args);

System.out.println("List beans pada Spring Boot adalah :");

String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}

q> Hasilnya adalah :

List beans pada Spring Boot adalah :
$autoCreateChannelCandidates
DefaultConfiguringBeanFactoryPostProcessor
IntegrationConfigurationBeanFactoryPostProcessor
_org.springframework.integration.errorLogger
authenticationEventPublisher
authenticationManager
authenticationManagerBuilder
autowiredWebSecurityConfigurersIgnoreParents
bankSoalRepository
basicErrorController
beanNameHandlerMapping
beanNameViewResolver
bootDefaultingAuthenticationConfigurerAdapter
bootGlobalAuthenticationConfigurationAdapter
channelInitializer
characterEncodingFilter
converterRegistrar
dataSource
dataSourceInitializedPublisher
dataSourceInitializer
dataSourceInitializerPostProcessor
datatypeChannelMessageConverter
defaultServletHandlerMapping
defaultTemplateResolver
defaultViewResolver
delegatingApplicationListener
dispatcherServlet
dispatcherServletRegistration
embeddedServletContainerCustomizerBeanPostProcessor
enableGlobalAuthenticationAutowiredConfigurer
entityManagerFactory
entityManagerFactoryBuilder
error
errorAttributes
errorChannel
faviconHandlerMapping
faviconRequestHandler
foo
globalChannelInterceptorProcessor
handlerExceptionResolver
hdrTestRepository
hiddenHttpMethodFilter
http.mappers.CONFIGURATION_PROPERTIES
httpRequestHandlerAdapter
ignoredPathsWebSecurityConfigurerAdapter
integrationConversionService
integrationEvaluationContext
integrationGlobalProperties
integrationHeaderChannelRegistry
integrationRequestMappingHandlerMapping
jacksonGeoModule
jacksonObjectMapper
jacksonObjectMapperBuilder
jdbcTemplate
jpaMappingContext
jpaVendorAdapter
kontakRepository
layoutDialect
mappingJackson2HttpMessageConverter
mbeanExporter
mbeanServer
messageBuilderFactory
messageConverters
multipart.CONFIGURATION_PROPERTIES
multipartConfigElement
multipartResolver
mvcContentNegotiationManager
mvcConversionService
mvcPathMatcher
mvcResourceUrlProvider
mvcUriComponentsContributor
mvcUrlPathHelper
mvcValidator
mvcViewResolver
namedParameterJdbcTemplate
nullChannel
objectNamingStrategy
objectPostProcessor
offlineTest
openEntityManagerInViewInterceptor
org.springframework.aop.config.internalAutoProxyCreator
org.springframework.boot.autoconfigure.AutoConfigurationPackages
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$JdkDynamicAutoProxyConfiguration
org.springframework.boot.autoconfigure.condition.BeanTypeRegistry
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration$IntegrationConfiguration
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$DataSourceInitializerConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration$TransactionManagementConfiguration
org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration
org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration$TomcatDataSourcePoolMetadataProviderConfiguration
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration
org.springframework.boot.autoconfigure.jta.JtaAutoConfiguration
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration
org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration$JpaWebMvcConfiguration
org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration
org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration$AuthenticationManagerConfigurationListener
org.springframework.boot.autoconfigure.security.BootGlobalAuthenticationConfiguration
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration
org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration
org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration$ApplicationNoWebSecurityConfigurerAdapter
org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration$WebMvcSecurityConfigurationConditions
org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration$WebMvcSecurityConfigurationConditions$DefaultWebMvcSecurityConfiguration
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$DefaultTemplateResolverConfiguration
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafSecurityDialectConfiguration
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafViewResolverConfiguration
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafWebLayoutConfiguration
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration
org.springframework.boot.autoconfigure.web.GsonHttpMessageConvertersConfiguration
org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration
org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration
org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration$TomcatWebSocketConfiguration
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.store
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalPersistenceAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.data.repository.core.support.RepositoryInterfaceAwareBeanPostProcessor
org.springframework.data.web.config.SpringDataJacksonConfiguration
org.springframework.data.web.config.SpringDataWebConfiguration
org.springframework.integration.config.IdGeneratorConfigurer#0
org.springframework.integration.expression.IntegrationEvaluationContextAwareBeanPostProcessor#0
org.springframework.integration.internalMessagingAnnotationPostProcessor
org.springframework.orm.jpa.SharedEntityManagerCreator#0
org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration
org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration
org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration
org.springframework.security.config.annotation.web.servlet.configuration.WebMvcSecurityConfiguration
org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration
org.springframework.transaction.config.internalTransactionAdvisor
pageableResolver
persistenceExceptionTranslationPostProcessor
privilegeEvaluator
propertySourcesPlaceholderConfigurer
requestContextListener
requestDataValueProcessor
requestMappingHandlerAdapter
requestMappingHandlerMapping
resourceHandlerMapping
roleRepository
runnumRepository
securityDialect
securityFilterChainRegistration
securityProperties
serverProperties
simpleControllerHandlerAdapter
sortResolver
spring.datasource.CONFIGURATION_PROPERTIES
spring.http.encoding.CONFIGURATION_PROPERTIES
spring.jackson.CONFIGURATION_PROPERTIES
spring.jpa.CONFIGURATION_PROPERTIES
spring.jta.CONFIGURATION_PROPERTIES
spring.mvc.CONFIGURATION_PROPERTIES
spring.resources.CONFIGURATION_PROPERTIES
spring.thymeleaf.CONFIGURATION_PROPERTIES
springSecurityFilterChain
stringHttpMessageConverter
taskScheduler
tempRepository
templateEngine
thymeleafResourceResolver
thymeleafViewResolver
toStringFriendlyJsonNodeToStringConverter
tomcatEmbeddedServletContainerFactory
tomcatPoolDataSourceMetadataProvider
transactionAttributeSource
transactionInterceptor
transactionManager
userRepository
viewControllerHandlerMapping
viewResolver
webSecurityExpressionHandler
websocketContainerCustomizer

Alhamdulillah

install tinymce pada thymeleaf

Coba tinymce pada thymeleaf

Bismillah

Sebelumnya sudah mencoba untuk menggunakan tinymce di html biasa, bagaiama klo di Thymeleaf ?

q> Konsepnya sama dengan menggunakan di html

q> Donwload , extract, kemudian panggil pada file htmlnya

q> Karena thymeleaf disini menggunakan spring boot, maka kita tambahkan registry untuk resourceHandlernya seperti ini :

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/bootstrap/**").addResourceLocations("classpath:/static/bootstrap/3.1.0/");
registry.addResourceHandler("/jq/**").addResourceLocations("classpath:/static/jquery/");
registry.addResourceHandler("/jqueryui/**").addResourceLocations("classpath:/static/jqueryui/");
registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/images/");
registry.addResourceHandler("/datepicker/**").addResourceLocations("classpath:/static/datepicker/");
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");
registry.addResourceHandler("/tinymce/**").addResourceLocations("classpath:/static/tinymce/");
/*linux*/
//registry.addResourceHandler("/foto/**").addResourceLocations("file:///home/saifi/Desktop/foto/");
/*windows*/


}

q> Ini coding untuk htmlnya :


<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Coba TinyMce</title>
<link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap.min.css}" />
<script type="text/javascript" th:src="@{/bootstrap/js/bootstrap.min.js}"></script>
<script type="text/javascript" th:src="@{/tinymce/js/tinymce/tinymce.min.js}"></script>

<script type="text/javascript">
tinymce.init({
selector: '#mytextarea',
images_upload_base_path: '/some/basepath'
});
</script>
</head>
<body>

<div th:include="header :: header"></div>
<div class="container">
<h1 th:inline="text">Coba TinyMce</h1>
<form action="" th:action="@{/soal/processtiny/}" method="post">
<textarea id="mytextarea" name="data" rows="" cols=""></textarea><br/>
<input type="submit" value="Kirim" class="btn btn-success" />
</form>
<label th:text="${hasil}">tes</label>

</div>

</body>
</html>

q> Dan ini untuk controllernya :

@RequestMapping(value = "/cobatiny", method = RequestMethod.GET)
public String cobaTinyMce(){
return "cobatiny";
}
@RequestMapping(value = "/processtiny", method = RequestMethod.POST)
public String processTiny(@RequestParam("data") String data, Model model){
model.addAttribute("hasil", data);
return "cobatiny";
}

q> Dan hasilnya adalah :
coba_tinymce_thymeleaf

 

Alhamdulillah

@Secured pada controller spring boot

Bagaiamana sebuah controller pada aplikasi spring boot hanya bisa diakases oleh user yang mempunyai ROLE admin ?

Bismillah

misalnya kita mempunyai sebuah controller seperti ini :

@Controller
@RequestMapping("/kontak")
@Secured("ROLE_ADMIN")
public class KontakController {
@RequestMapping("/save")
public void save(){
}
}

Maka untuk mengakses controller tersebut hanya user-user yang mempunyai role admin saja yang bisa mengaksesnya, selain user tersebut maka akan muncul error Access is denied

Catatan :
aplikasi menggunakan spring boot, spring data jpa, spring security, thymeleaf dan database mariadb

Alhamdulillah

belajar spring boot

Spring boot,

Bismillah

q> Ini praktek dari halaman :
http://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-first-application.html

q> Cek versi java

java -version
java version "1.7.0_67"
Java(TM) SE Runtime Environment (build 1.7.0_67-b01)
Java HotSpot(TM) Server VM (build 24.65-b04, mixed mode)

q> Cek versi maven

mvn -v
Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-15T01:29:23+08:00)
Maven home: /usr/local/apache-maven/apache-maven-3.2.5
Java version: 1.7.0_67, vendor: Oracle Corporation
Java home: /opt/java/32/jdk1.7.0_67/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.13.0-24-generic", arch: "i386", family: "unix"

q> Buat folder boot

mkdir boot

q> Masuk ke dalam folder boot

cd boot

q> Buat file pom.xml

gedit pom.xml

q> Copy-paste code ini ke pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.1.RELEASE</version>
</parent>

<!-- Additional lines to be added here... -->

</project>

q> Jalankan perintah ini

mvn package

Perintah di atas akan membuat folder target pada project.

q>Kemudian jalankan perintah ini

mvn dependency:tree

Pada saat ini, project belum ada dependency terhadap library lain. Seperti ini gambar tree dependency :

Selection_658

q> Tambahkan dependencies pada pom.xml

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
q> Kemudian jalankan lagi perintah ini :
mvn dependency:tree

Pada saat ini sudah terlihat dependency, seperti pada gambar ini :

Selection_659

q> Ketikkan perintah ini untuk membuat struktur folder src/main/java, maven akan melakukan compile terhadap file java yang berada pada src/main/java

mkdir -p src/main/java

q> Buat file controller,

gedit src/main/java/Example.java 

q> Copy-paste code ini ke dalam file Example.java


import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {

@RequestMapping("/")
String home() {
return "Hello World!";
}

public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}

}

q> Menjalankan aplikasi spring boot, pada posisi path /boot, jalankan perintah ini :

mvn spring-boot:run

q> Buka browser, dan akses alamat : localhost:8080

Selection_656

 

q> Struktur project folder dan file :
Selection_657

 

q> Menjadikan project spring-boot menjadi file jar

q> Tambahkan code ini pada file pom.xml tepat di bawah tag dependencies

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

q> Jalankan lagi perintah ini :

mvn package

q> Maka akan menghasilkan file myproject-0.0.1-SNAPSHOT.jar pada folder target

q> Jalankan file jar ini menggunakan perintah :

java -jar target/myproject-0.0.1-SNAPSHOT.jar

q> Kemudian buka browser dan akses halaman localhost:8080

q> Waw, projectnya menjadi file jar dan bisa dijalankan dengan java -jar

q> Project ini sudah di-upload ke github : https://github.com/saifiahmada/boot

Alhamdulillah

client side pagination dan sorting spring mvc datatables

membuat paging (pagination) dan sorting, spring mvc + datatables + bootstrap

Bismillah

q> Melanjukan tulisan sebelumnya
https://saifiahmada.wordpress.com/2014/12/27/client-side-validator-menggunakan-jquery-validation/

q> Hasil yang akan didapat pada tulisan kali ini  :

Selection_641

q> Langkah2 praktek :

1. buat bean entity User

package com.saifiahmada.maven.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Size;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.NotBlank;

@Entity
public class User {

	@Id
	@GeneratedValue(generator="system-uuid")
	@GenericGenerator(name="system-uuid", strategy="uuid2")
	private String id;
	@Size(min=3, message="minimal 3 karakter")
	@NotBlank(message="tidak boleh kosong")
	private String username;

	@Size(min=3, message="minimal 3 karakter")
	@NotBlank(message="tidak boleh kosong")
	private String password;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	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;
	}

}

2. buat interface UserRepository

package com.saifiahmada.maven.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.saifiahmada.maven.entity.User;

public interface UserRepository extends JpaRepository<User, String>  {

}

3. buat class UserService

package com.saifiahmada.maven.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.saifiahmada.maven.entity.Partner;
import com.saifiahmada.maven.entity.User;
import com.saifiahmada.maven.repository.UserRepository;

@Service
public class UserService {

	@Autowired
	private UserRepository userRepository;

	public List<User> findAll() {
		return userRepository.findAll();
	}

	public void save(User user) {
		userRepository.save(user);
	}

	public User findOne(String id) {
		return userRepository.findOne(id);
	}

	public void delete(String id) {
		userRepository.delete(id);
	}

}

4. buat class UserController

package com.saifiahmada.maven.controller;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.saifiahmada.maven.entity.User;
import com.saifiahmada.maven.service.UserService;

@Controller
@RequestMapping(value = "/user")
public class UserController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserService userService;

	@RequestMapping(value="/form", method=RequestMethod.GET)
	public String form(Model model){
		model.addAttribute("entity", new User());
		return "user-form";
	}

	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String list(Model model){
		model.addAttribute("entities", userService.findAll());
		return "user-list";
	}

	@RequestMapping(value="/add", method=RequestMethod.POST)
	public String add(@Valid @ModelAttribute("entity") User user, BindingResult result) {

		if (result.hasErrors()) {
			return "user-form";
		}
		userService.save(user);
		return "redirect:/user/form.html?success=true";
	}

	@RequestMapping(value="/edit/{id}")
	public String edit(@PathVariable("id") String id, Model model){
		model.addAttribute("entity", userService.findOne(id));
		return "user-form";
	}

	@RequestMapping(value="/delete/{id}")
	public String delete(@PathVariable("id") String id, Model model){
		userService.delete(id);
		model.addAttribute("entity", new User());
		model.addAttribute("listModel", userService.findAll());
		return "user-form";
	}

}

5. buat file user-list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ include file="../layout/taglib.jsp" %>

<a href="/user/form.html" class="btn btn-success">Add</a>
<br/>
<br/>

<table id="entity" class="table table-bordered table-hover table-striped">
	<thead>
		<tr>
			<th>Username</th>
			<th>Password</th>
			<th>Edit</th>
			<th>Delete</th>
		</tr>
	</thead>
	<tbody>
		<c:forEach items="${entities}" var="l">
			<tr>
				<td>${l.username }</td>
				<td>${l.password }</td>
				<td><a href="/user/edit/${l.id}.html">Edit</a></td>
				<td><a href="/user/delete/${l.id}.html">Delete</a></td>
			</tr>
		</c:forEach>
	</tbody>
</table>

<script type="text/javascript">
	$(document).ready(function() {
		var table = $('#entity').DataTable();
	});
</script>

6. buat file user-form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@ include file="../layout/taglib.jsp"%>

<c:if test="${param.success eq true }">
	<div class="alert alert-success">Data berhasil disimpan</div>
</c:if>

<form:form commandName="entity" action="/user/add.html"
	cssClass="form-horizontal formUser">

	<c:if test="${ ! empty entity.id}">
		<div class="form-group">
			<label for="id" class="col-sm-2 control-label">Id</label>
			<div class="col-sm-10">
				<form:input path="id" cssClass="form-control" readonly="true" disabled="true" />
				<form:hidden path="id"/>
			</div>
		</div>
	</c:if>

	<div class="form-group">
		<label for="username" class="col-sm-2 control-label">Username</label>
		<div class="col-sm-10">
			<form:input path="username" cssClass="form-control" />
			<form:errors path="username" />
		</div>
	</div>

	<div class="form-group">
		<label for="password" class="col-sm-2 control-label">Password</label>
		<div class="col-sm-10">
			<form:input path="password" cssClass="form-control" />
			<form:errors path="password" />
		</div>
	</div>

	<input type="submit" value="Simpan" class="btn btn-success" />
	<a href="/user/form.html" class="btn btn-success">Reset</a>
	<a href="/user/list.html" class="btn btn-success">List</a>

</form:form>

<script type="text/javascript" >
	$(document).ready( function() {

		$(".formUser").validate(
			{
				rules : {
					username : {
						required : true,
						minlength : 3
					},
					password : {
						required : true,
						minlength : 3
					}

				},
				highlight : function (element) {
					$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
				},
				unhighlight : function (element) {
					$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
				}
			}
		);

	} );
</script>

7. tambahkan definition pada file general.xml

<definition name="user-list" extends="common">
		<put-attribute name="title" value="User List" />
		<put-attribute name="body" value="/WEB-INF/jsp/user-list.jsp" />
		<put-attribute name="current" value="user-list" />
	</definition>

	<definition name="part-form" extends="common">
		<put-attribute name="title" value="Part Form" />
		<put-attribute name="body" value="/WEB-INF/jsp/part-form.jsp" />
		<put-attribute name="current" value="part-list" />
	</definition>

8. tambahkan link untuk menu User pada file classic.jsp

<li class="${current == 'user-list' ? 'active' : '' }"><a href="/user/list.html">User</a></li>

9. pagination dan sorting pada sisi client (client side)

pada halaman user-list.jsp terdapat script javascript seperti ini

<script type="text/javascript">
	$(document).ready(function() {
		var table = $('#entity').DataTable();
	});
</script>

dari script di atas ada method DataTable(), method inilah yang membuat list user mempunyai paging dan sorting,
tetapi untuk script tersebut masih melakukan paging dan sorting dari sisi client (client side)

Berdasarkan http://www.datatables.net/
dijelaskan :

DataTables is a plug-in for the jQuery Javascript library.
It is a highly flexible tool, based upon the foundations of progressive enhancement,
and will add advanced interaction controls to any HTML table.

Untuk mengintegrasikan datatables dan bootstrap 3 (karena aplikasi ini menggunakan bootstrap 3) buka halaman ini
https://datatables.net/examples/styling/bootstrap.html

q> Untuk user-form.jsp juga sudah ada client validator

Selection_642

q> Tampilan ketika form berhasil disimpan

Selection_643

q> Sorting client side

Selection_644

Alhamdulillah