viernes, 28 de diciembre de 2012

Hibernate - Queries

Load an entity

There are two forms to get an entity with the methods load() or get().

public Category getCategory(Long catId) throws DataAccessException {
    return (Category) this.getSessionFactory().getCurrentSession()
                                              .load(Category.class, catId); }

public Category getCategory(Long catId) throws DataAccessException {
    return (Category) this.getSessionFactory().getCurrentSession()
.get(Category.class, catId); }
The difference are:
  • load()
    • Throws an exception if there isn't any row.
    • Has performane benefits.
  • get()
    • Return null if there isn't any row.
HibernateTemplate - Using Parameters with findByNamedParam
In case of use only one parameter, you need the query, parameter name and the value.
public List<ArtEntity> getArtworkInCategory(Long catId)
                                             throws DataAccessException {
    return this.getHibernateTemplate().findByNamedParam(
        "select art from Category cat " +
        "join cat.artEntities art " +
        "where cat.id = :catId ",
        "catId", catId
    );
}

In case of many parameters, you need the query, array with the parameters and the array with corresponding values

public Person authenticatePerson(String username, String password)
                   throws DataAccessException, AuthenticationException {

    List<Person> validUsers = this.getHibernateTemplate().findByNamedParam(
        "select people from Person people where" +
        "people.username = :username " +
        "and people.password = :password",
         new String[] {"username", "password"},
         new String[] {username, password }
    );

    if (validUsers == null || validUsers.size() <= 0) {
        throw new AuthenticationException("No users found");
    } else {
        return validUsers.get(0);
    }
}

Hibernate Core APIs - Using Parameters

public Person authenticatePerson(String username, String password)
                      throws DataAccessException, AuthenticationException {

    Person validUser =
        (Person) this.getSessionFactory().getCurrentSession().createQuery(
            "select people from Person people where" +
            "people.username = :username " +
            "and people.password = :password")
            .setString("username", username)
            .setString("password", password)
            .uniqueResult()
        );

    if (validUser == null) {
            throw new AuthenticationException("No users found");
} else {
        return validUser;
    }
}











martes, 25 de diciembre de 2012

Hibernate - hashcode / equals


Implementation of the methods equals and hashCode.



@Override
 public boolean equals(Object o) {
     if (this == o) return true;
     if (!(o instanceof Category)) return false;

      Category category = (Category) o;
     if (categoryName != null ?
             !categoryName.equals(category.categoryName) : category.categoryName != null) {
         return false;
     } else {
         return true;
     }
 }


 @Override
 public int hashCode() {
     return categoryName != null ? categoryName.hashCode() : 0;
 }

HIbernate - Annotations

Hibernate annotations

@Entity - To persist the class
@Basic  - Customized the persistance as lazy mode or aspects
@Transient  - Don't persist
@Temporal  - To persist dates  Ex. @Temporal(TemporalType.TIMESTAMP)
@Table  - To use a different name from table Ex. @Table(name = "HOGWASH")
@Column  - To map a column with different name @Column(name = "commentText")
@Id  - Define attribute as primary key

@GeneratedValue  - Use with @Id to create an identifier, by default AUTO. Ex @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="COMMENT_ID_SEQ") to specify a different behavior


@OneToMany  - To establish the relation. Ex 
@OneToMany(orphanRemoval = true, cascade = { javax.persistence.CascadeType.ALL }) 
orphanRemoval - Delete any dereferenced
javax.persistence.CascadeType  - The eentity will be affected in any save/update

@Cache  - First try to find an instance in the cache, helpful for improve performance  Ex. @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
CacheConcurrencyStrategy.NONSTRICT_READ_WRITE -  In case of update the cache will be invalid

@Inheritance  - Ex. @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
Types : Implicit polymorphism, Table-per-hierarchy, Table-per-subclass, Table-per-concrete-class 

@ManyToMany  - Ex. @ManyToMany(mappedBy = "artEntities")
mappedBy -  Define which table owns the relationship






lunes, 24 de diciembre de 2012

Web.xml - Servlet


There are two way to declare the configuration file


  • You can declare the file with the configuration in the tag <init-param>
   <servlet> 
     <servlet-name>galleryDispatcher</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
     <init-param> 
       <param-name>contextConfigLocation</param-name> 
       <param-value> 
                 /WEB-INF/spring/spring-master-web.xml 
             </param-value> 
     </init-param> 
     <load-on-startup>1</load-on-startup> 
   </servlet> 

  • The second form is creating a file named galleryDispatcher-servlet.xml in WEF-INF/.  In this case automatically are going to look for a file "servlet-name"-servlet.xml



  <servlet> 
     <servlet-name>galleryDispatcher</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
     <load-on-startup>1</load-on-startup> 
   </servlet> 







jueves, 20 de diciembre de 2012

Spring - Annotations

@Repository annotation should be used to indicate those classes that compose the DAO layer.

@Service annotation can be used to designate those classes that are part of an application's service facade, which are used in the web layer to handle requests

@Controller annotation denotes the presence of a POJO that should be used for Spring MVC interactions. Defines a service facade.

jueves, 13 de diciembre de 2012

Spring - Load properties

(application-context.xml)
In your application-context.xml, use the tag context:property-placeholder to define the property file where you have the values of your bean properties.


The value of location is the rath of your file:

<context:property-placeholder location="classpath*:spring/*.properties" />

In case that you have your property file outside your project:

<context:property-placeholder location=""file:///var/conf/conf.properties"/>
After define your file properties with the values:

db.name = test
db.user = user
db.password = password
db.port = 3306


Finally you can use the properties in your beans:


<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value= "${db.user}" />
<property name="password" value="${db.password}" />

</bean>


(web.xml)
In the web.xml don´t forget to include the file application-context.xml


  <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/application-context.xml
</param-value>
</context-param>




Java Project Structure

In Eclipse to add the structure folders choose New -> Soure Folder
Select the chech box "Update exclusion filters into other source folders to solve nesting"



  • Within the project_name folder, we'll create the folders that are customary for a Java application:

project_name/src
project_name/src/main
project_name/src/main/java
project_name/src/main/resources


  • For web applications, we need a webapp and WEB-INF folder:

project_name/src/main/webapp
project_name/src/main/webapp/WEB-INF

  • We also need to create the folders that are required for unit testing our application:

project_name/src/test
project_name/src/test/java
project_name/src/test/resources

  • And finally, we'll create the two folders where Spring configuration files are ordinarily placed:

project_name/src/main/webapp/WEB-INF/spring