Showing posts with label hibernate. Show all posts
Showing posts with label hibernate. Show all posts

Spring Security + Hibernate : Enabling database login via Annotations

Hibernate Entities:

Employee.java
===========
package com.mycompany.myapp.entity;

import javax.persistence.*;
import java.util.*;

@Entity
@Table(name = "employee")
public class Employee {

    private long id;
    private String username;
    private String password;

    @Column(name = "enabled", columnDefinition = "boolean default true",
     nullable = false)
    private Boolean enabled = true;

    @Id
    @GeneratedValue
    @Column(name = "id")
    public long getId() {
        return id;
    }

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

//...

//other getters, setters

}

EmployeeRoles.java:
============
package com.mycompany.myapp.entity;

import javax.persistence.*;


@Entity
@Table(name = "employee_roles")
public class EmployeeRoles{

 private int id;
 private String employeeCode;
 private String role;

 @Id
 @GeneratedValue
 @Column(name = "id")
 public int getId()
 {

     return id;

 }

 
 public void setId(int id)
 {

     this.id = id;

 }

//other getters, setters
}

Initial Roles:

src/main/resources/import.sql:
====================================
insert into employee_roles(employee_code,role) 
values('SOME_EMPLOYEE_CODE','ROLE_USER');

Spring Security config:

WebSecurityConfig.java:
===================
package com.mycompany.myapp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication
.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders
.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration
.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration
.EnableWebSecurity;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation
.ResourceHandlerRegistry;
import javax.sql.*;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/webjars/**","/webjars/","/img/**",
                 "/styles/**","/js/**","/api/1.0/get**", "/about.html")
                 .permitAll().anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
                
    }


    @Autowired
    DataSource dataSource;
    
    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) 
throws Exception {
         
            auth.jdbcAuthentication().dataSource(dataSource)
       .usersByUsernameQuery(
          "select username,password, enabled 
                           from employee where username=?")
         .authoritiesByUsernameQuery(
            "select employee_code, role 
                        from employee_roles where employee_code=?");
    }
}

JPA : Can not run ddl-auto=update with Spring Boot

Caused by: org.postgresql.util.PSQLException: ERROR: column i.indproc does not exist


This may happen while trying to update development db schema without loosing data and adding schema updates into development db:


  1. spring.jpa.hibernate.ddl-auto=update

Problem is with Postgresql JDBC driver 9.1-901-1.jdbc4:

  1. compile group: 'postgresql', name: 'postgresql', version: '9.1-901-1.jdbc4'
Upgrade it to latest version 42.2.5 in build.gradle:

  1. compile group: 'org.postgresql', name: 'postgresql', version: '42.2.5'
Maven repository:
https://mvnrepository.com/artifact/org.postgresql/postgresql/42.2.5

maven:
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.5</version>
</dependency>

Spring 3 Hibernate 4 Annotations Entity Manager PostgreSQL maven standalone example

Create the sample postgresql database at first in PgAdmin :
  1. CREATE DATABASE "TESTS"
  2. WITH OWNER = postgres
  3. ENCODING = 'UTF8'
  4. TABLESPACE = pg_default
  5. CONNECTION LIMIT = -1;

Then create the table in databse 'TESTS':
  1. CREATE TABLE USERS (
  2. ID serial NOT NULL,
  3. USERNAME text NOT NULL,
  4. NAME text NOT NULL
  5. );

Download the example from github.Build(mvn clean install) And run Main.java