Anuncio

Mostrando entradas con la etiqueta spring. Mostrar todas las entradas
Mostrando entradas con la etiqueta spring. Mostrar todas las entradas

jueves, 9 de octubre de 2014

Problemas UTF-8 en Tomcat y Spring

WEB.XML


<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>






SERVER.XML

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="UTF-8"/>



Fuente: http://www.danilat.com/weblog/2011/03/05/configuracion-tomcat-para-trabajar-con-utf8/

jueves, 25 de septiembre de 2014

Spring Data JPA

Querydsl 





BooleanBuilder



CollectionExpression




JPA Query Expressions (JPQL / Criteria)





Spring Data JPA + Querydsl Integration







Advanced Spring Data JPA - Specifications and Querydsl








Interface JpaRepository<T,ID extends Serializable>












Hibernate Annotations





Spring Data JPA - Reference Documentation















Fine-tuning Spring Data repositories





Customizing Spring Data JPA Repository





SpEL support in Spring Data JPA @Query definitions



 JPA Query







Named Native Query





Anotaciones en JPA para sobrevivir a una primera persistenica


http://softwareyotrasdesvirtudes.com/2012/09/20/anotaciones-en-jpa-para-sobrevivir-a-una-primera-persistenica/


http://docs.oracle.com/javaee/5/api/javax/persistence/JoinColumn.html



JPA Annotations for Mapping (ORM)



 UniqueConstraint




Embeddable

Annotation ManyToOne







7.  Additional JPA Mappings




FetchMode




JPA vs Hibernate



Chapter 2. Why JPA?

http://docs.oracle.com/cd/E24329_01/apirefs.1211/e24396/ejb3_overview_why.html




JPA Implementation Patterns: Saving (Detached) Entities


http://blog.xebia.com/2009/03/23/jpa-implementation-patterns-saving-detached-entities/



Chapter 6.  Java Persistence Entity Operations


Describe how to manage entities, including using the EntityManager API and the cascade option.






 javax.validation.constraints





hibernate validator




5 minutes with – Jpa transaction




ET TRANSACTION ISOLATION LEVEL (Transact-SQL)



Hibernate Transaction Annotation Configuration

jueves, 18 de septiembre de 2014

EntityManager get Hibernate Session Factory

org.hibernate.Session hibernateSession = (Session)entityManager.getDelegate();



FUENTE: http://www.theserverside.com/tip/How-to-get-the-Hibernate-Session-from-the-JPA-20-EntityManager

@Transactional JPA Propagation - Isolation

PROPAGATION_REQUIRED = 0; If DataSourceTransactionObject T1 is already started for Method M1.If for another Method M2 Transaction object is required ,no new Transaction object is created .Same object T1 is used for M2
PROPAGATION_MANDATORY = 2; method must run within a transaction. If no existing transaction is in progress, an exception will be thrown
PROPAGATION_REQUIRES_NEW = 3; If DataSourceTransactionObject T1 is already started for Method M1 and it is in progress(executing method M1) .If another method M2 start executing then T1 is suspended for the duration of method M2 with new DataSourceTransactionObject T2 for M2.M2 run within its own transaction context
PROPAGATION_NOT_SUPPORTED = 4; If DataSourceTransactionObject T1 is already started for Method M1.If another method M2 is run concurrently .Then M2 should not run within transaction context. T1 is suspended till M2 is finished.
PROPAGATION_NEVER = 5; None of the methods run in transaction context.
An isolation level: It is about how much a transaction may be impacted by the activities of other concurrent transactions.It a supports consistency leaving the data across many tables in a consistent state. It involves locking rows and/or tables in a database.
The problem with multiple transaction
Scenario 1.If T1 transaction reads data from table A1 that was written by another concurrent transaction T2.If on the way T2 is rollback,the data obtained by T1 is invalid one.E.g a=2 is original data .If T1 read a=1 that was written by T2.If T2 rollback then a=1 will be rollback to a=2 in DB.But,Now ,T1 has a=1 but in DB table it is changed to a=2.
Scenario2.If T1 transaction reads data from table A1.If another concurrent transaction(T2) update data on table A1.Then the data that T1 has read is different from table A1.Because T2 has updated the data on table A1.E.g if T1 read a=1 and T2 updated a=2.Then a!=b.
Scenario 3.If T1 transaction reads data from table A1 with certain number of rows. If another concurrent transaction(T2) inserts more rows on table A1.The number of rows read by T1 is different from rows on table A1
Scenario 1 is called Dirty reads
Scenario 2 is called Nonrepeatable reads
Scenario 3 is called Phantom reads .
So,isolation level is the extend to which Scenario 1 ,Scenario 2 ,Scenario 3 can be prevented. You can obtained complete isolation level by implementing locking.That is preventing concurrent reads and writes to the same data from occurring.But it affects performance .The level of isolation depends upon application to application how much isolation is required.
ISOLATION_READ_UNCOMMITTED :Allows to read changes that haven’t yet been committed.It suffer from Scenario 1 ,Scenario 2 ,Scenario 3
ISOLATION_READ_COMMITTED:Allows reads from concurrent transactions that have been com- mitted.It may suffer from Scenario 2 ,Scenario 3 . Because other transactions may be updating the data.
ISOLATION_REPEATABLE_READ:Multiple reads of the same field will yield the same results untill it is changed by itself.It may suffer from Scenario 3.Because other transactions may be inserting the data
ISOLATION_SERIALIZABLE: Scenario 1,Scenario 2,Scenario 3 never happens.It is complete isolation.It involves full locking.It affets performace because of locking.


Shared Entity Manager Transactions



FUENTE: http://tomee.apache.org/examples-trunk/transaction-rollback/README.html

Spring Hibernate Integration Using Java Persistence API




FUENTE: http://www.studytrails.com/frameworks/spring/spring-hibernate-jpa.jsp

jueves, 11 de septiembre de 2014

Libros y Documentacion Spring, Hibernate, Java Server Faces




FUENTE: http://userexception.blogspot.com.es/2011/11/libros-y-documentacion-sobre-jsf-spring.html

JPassion.com Courses


Live, Instructor-led, Online Codecamps


martes, 26 de agosto de 2014

Jetty Embedded webapp



Create Maven WebApp with Jetty in Netbeans
http://www.youtube.com/watch?v=YaP3LQVzB-Q


How to create a war and jar from a web project?
http://stackoverflow.com/questions/15509893/how-to-create-a-war-and-jar-from-a-web-project


Executable WARs with Jetty
http://eclipsesource.com/blogs/2009/10/02/executable-wars-with-jetty/

Creating an executable jar executing a war file with embedded jetty
http://stackoverflow.com/questions/15919568/creating-an-executable-jar-executing-a-war-file-with-embedded-jetty

Embedded Jetty Executable JAR
http://blog.anvard.org/articles/2013/10/09/embedded-jetty-executable-maven.html

Embedding Jetty
http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html

create a executable jar using maven and jetty
http://stackoverflow.com/questions/20491407/create-a-executable-jar-using-maven-and-jetty

Setting up embedded Jetty 8 and Spring MVC with Maven
http://steveliles.github.io/setting_up_embedded_jetty_8_and_spring_mvc_with_maven.html

Runnable WAR With Embedded Jetty Server
http://blog.dinauer.at/runnable-war-with-embedded-jetty-server/

Configuring Jetty JSP support in embedded mode in Maven project
http://stackoverflow.com/questions/4235082/configuring-jetty-jsp-support-in-embedded-mode-in-maven-project

web app started by jetty runner not working with jstl tags?
http://stackoverflow.com/questions/9333403/web-app-started-by-jetty-runner-not-working-with-jstl-tags

Jetty/Howto/Configure JSP
http://wiki.eclipse.org/Jetty/Howto/Configure_JSP

Disable Maven warning message - “Selected war files include a WEB-INF/web.xml which will be ignored”
http://stackoverflow.com/questions/4342245/disable-maven-warning-message-selected-war-files-include-a-web-inf-web-xml-wh



Newbie Guide to Jetty
http://docs.codehaus.org/display/JETTY/Newbie+Guide+to+Jetty

Starting up Jetty

  • jetty-runner.jar - fast and easy way to run your webapp, without needing to install and administer a jetty distro. Run it using java -jar jetty-runner.jar webappcontext. Further instructions can be found in the blog entry linked to above.
  • start.jar - start from within your Jetty installation. Run it using java -jar start.jar configuration files
  • embed Jetty into your application
  • as a distribution package (RPM, .deb)
  • Maven Jetty Plugin



WAR FILES VS. JAVA APPS WITH EMBEDDED SERVERS
http://steveperkins.net/war-files-vs-embedded-servers/

a jetty server app can work in eclipse but can't in Windows Console?
http://stackoverflow.com/questions/11094029/a-jetty-server-app-can-work-in-eclipse-but-cant-in-windows-console


Jetty/Tutorial/Jetty and Maven HelloWorld
http://wiki.eclipse.org/Jetty/Tutorial/Jetty_and_Maven_HelloWorld


Rapid Testing Using the Jetty Plugin
http://maven.apache.org/plugins/maven-war-plugin/examples/rapid-testing-jetty6-plugin.html

maven jetty - org.mortbay.jetty vs org.eclipse.jetty
http://stackoverflow.com/questions/15386461/maven-jetty-org-mortbay-jetty-vs-org-eclipse-jetty

Embedding Jetty with Netbeans 7 (and Maven)
http://www.giantflyingsaucer.com/blog/?p=3023

Embedded vs Stand alone Tomcat ( HTTP ) server
http://stackoverflow.com/questions/20736356/embedded-vs-stand-alone-tomcat-http-server

-Dorg.apache.jasper.compiler.disablejsr199=true
http://www.eclipse.org/jetty/documentation/current/configuring-jsp.html

JSPs for embedded Jetty in Maven tests not compiling
http://stackoverflow.com/questions/23394842/jsps-for-embedded-jetty-in-maven-tests-not-compiling

Jetty/Howto/Using Jetty Runner
http://wiki.eclipse.org/Jetty/Howto/Using_Jetty_Runner

Running a web application (WAR) with embedded jetty server
http://stackoverflow.com/questions/21861019/running-a-web-application-war-with-embedded-jetty-server

Embedded Jetty : how to use a .war that is included in the .jar from which Jetty starts?
http://stackoverflow.com/questions/13434538/embedded-jetty-how-to-use-a-war-that-is-included-in-the-jar-from-which-jetty

Executable war file that starts jetty without maven
http://stackoverflow.com/questions/2458440/executable-war-file-that-starts-jetty-without-maven



jueves, 27 de marzo de 2014

Etiquetas básicas JSP en Java

Existen 5 etiquetas básicas JSP:
  • Scriptlets
  • Expresiones
  • Declaraciones
  • Directivas
  • Comentarios


1. Los scriptlets:

Permiten escribir cualquier código java que el compilador pueda interpretar dentro de la etiqueta  <% y %>.

<%
     System.out.println("Esto es una prueba");
%>

2. Expresiones:


Código java que devuelve como resultado un String que podemos incluir en la página JSP entre las etiquetas <%= y %>.

La fecha actual es <%= new Date() %>


3. Declaraciones:

También nos permite escribir código java al igual que los scriptlets pero a diferencia de estos dentro de las etiquetas de expresión no se permiten puntos y comas incluso si la misma expresión lo requiere.Es codigo java igual y va entre las etiquetas <%! y %>

<%= Math.sqrt(2) %>
<%= items[i] %>
<%= a + b + c %>
<%= new java.util.Date() %>

4. Directivas:

Las directivas influyen en la estructura que tendrá el servlet generado a partir de la página JSP. Hay tres tipos de directivas:
  • page: Tiene varios usos: importar clases de Java, fijar el tipo MIME de la respuesta, controlar el buffer de salida, etc.
  • include: Sirve para incluir código en la página antes de que se realice la compilación del JSP.
  • taglib: Se emplea cuando el JSP hace uso de etiquetas definidas por el usuario.
Entre las etiquetas <%@ y %>.

<%@ page import="java.util.Date" %>
<%@ page contentType="text/plain" %>
<%@ include file="fichero" %>

5. Comentarios:

Fragmentos de código que no son enviados al cliente ni interpretados por el compilador entre las etiquetas <%-- y --%>.

<%-- Estoy comentando el código --%>



FUENTE:




domingo, 2 de marzo de 2014

Como cargar Hibernate.Cfg.Xml desde otro directorio

Hibernate.cfg.xml suele estar en el root de tu proyecto, fuera de todo paquete. Si lo pones en otro directorio te aparecerá el siguiente error:
Initial SessionFactory creation failed.org.hibernate.HibernateException: 
/hibernate.cfg.xml not found
 
Exception in thread "main" java.lang.ExceptionInInitializerError
 at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:25)
 at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8)
 at com.mkyong.common.App.main(App.java:11)
Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
 at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
 at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1405)
 at org.hibernate.cfg.Configuration.configure(Configuration.java:1427)
 at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
 at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
 ... 2 more
Para decirle a Hibernate como encontrar hibernate.cfg.xml hay que modificar el argumento del método configure() como se muestra a continuación.
            SessionFactory sessionFactory = new Configuration()
            .configure("/com/companyname/example/hibernate.cfg.xml")
            .buildSessionFactory();
 
            return sessionFactory;

HibernateUtil.java

Aquí se muestra un ejemplo completo para cargarlo desde el directorio “/com/companyname/example/“.
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil {
 
 private static final SessionFactory sessionFactory = buildSessionFactory();
 
 private static SessionFactory buildSessionFactory() {
  try {
   // load from different directory
   SessionFactory sessionFactory = new Configuration().configure(
     "/com/companyname/example/hibernate.cfg.xml")
     .buildSessionFactory();
 
   return sessionFactory;
 
  } catch (Throwable ex) {
   // Make sure you log the exception, as it might be swallowed
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }
 
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
 
 public static void shutdown() {
  // Close caches and connection pools
  getSessionFactory().close();
 }
 
}

FUENTE: http://www.mkyong.com/hibernate/how-to-load-hibernate-cfg-xml-from-different-directory/

viernes, 21 de febrero de 2014

Desarrollando una aplicación Spring Framework MVC v3 + JPA paso a paso

Autor

Francisco Grimaldo Moreno (francisco.grimaldo@uv.es - Website)

Fuentes consultadas

Este tutorial es una adaptación del tutorial 'Developing a Spring Framework MVC application step-by-step' para la versión 3 de Spring Framework donde, además, la persistencia de datos se realiza mediante JPA. Una parte del texto, a su vez, proviene de la traducción al castellano realizada por David Marco Palao. Los tutoriales anteriores se pueden consultar en:
Versión de Spring utilizada: 3.2.0
Se permite la copia de este documento así como su distribución, siempre que sea de manera gratuita y que cada copia contenga este aviso de Copyright, tanto en soporte físico como electrónico.

Tabla de Contenidos
Descripción
1. Contenido
2. Software requerido
3. La aplicación que vamos a construir
1. Aplicacion Base y Configuracion del Entorno
1.1. Crear la estructura de directorios del proyecto
1.2. Crear 'index.jsp'
1.3. Desplegar la aplicación en el servidor
1.4. Comprobar que la aplicación funciona
1.5. Descargar Spring Framework
1.6. Modicar 'web.xml' en el directorio 'src/main/webapp/WEB-INF'
1.7. Crear el Controlador
1.8. Escribir un test para el Controlador
1.9. Crear la Vista
1.10. Compilar, desplegar y probar la aplicación
1.11. Resumen
2. Desarrollando y Configurando la Vista y el Controlador
2.1. Configurar JSTL y añadir un archivo de cabecera JSP
2.2. Mejorar el controlador
2.3. Separar la vista del controlador
2.4. Resumen
3. Desarrollando la Lógica de Negocio
3.1. Revisar la regla de negocio del Sistema de Mantenimiento de Inventario
3.2. Añadir algunas clases a la lógica de negocio
3.3. Resumen
4. Desarrollando la Interface Web
4.1. Añadir una referencia a la lógica de negocio en el controlador
4.2. Modificar la vista para mostrar datos de negocio y añadir soporte para archivos de mensajes
4.3. Añadir datos de prueba para rellenar algunos objetos de negocio
4.4. Añadir una ubicación para los mensajes
4.5. Añadir un formulario
4.6. Añadir un controlador de formulario
4.7. Resumen
5. Implementando Persistencia en Base de Datos
5.1. Creación y rellenado de la base de datos
5.2. Crear una implementacion para JPA de un Objeto de Acceso a Datos (DAO)
5.3. Implementar tests para la implementacion DAO sobre JPA
5.4. Resumen
6. Integrando la Aplicación Web con la Capa de Persistencia
6.1. Modificar la Capa de Servicio
6.2. Resolver los tests fallidos
6.3. Crear un nuevo contexto de aplicacion para configurar la capa de servicio
6.4. Test final de la aplicacion completa
6.5. Resumen
A. Descargar Proyecto Completo para Spring Tool Suite



FUENTE: http://www.uv.es/grimo/teaching/SpringMVCv3PasoAPaso/