Spring back end localhost requires login - spring

I'm trying to develop a cross-platform application, with Cordova in the front-end and using Spring in the back_end.
Basically, I started by the link between the database and generating the classes (models). Here's my application properties:
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = updateUnable to find column with logical name: program_id
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
# Server
server.port=8080
endpoints.cors.allowed-origins=*
I wanted to try if I'm getting the list in JSON form before I go to the backend. So I made an example to get the list of operators, the class Operator is declared like that:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.rest.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author gate11
*/
#Entity
#Table(catalog = "db_suivi", schema = "")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Operator.findAll", query = "SELECT o FROM Operator o")
, #NamedQuery(name = "Operator.findById", query = "SELECT o FROM Operator o WHERE o.id = :id")
, #NamedQuery(name = "Operator.findByOperatorFName", query = "SELECT o FROM Operator o WHERE o.operatorFName = :operatorFName")
, #NamedQuery(name = "Operator.findByOperatorLName", query = "SELECT o FROM Operator o WHERE o.operatorLName = :operatorLName")})
public class Operator implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
private Long id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
private String operatorFName;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 100)
private String operatorLName;
#JoinTable(name = "BadgeOperator", joinColumns = {
#JoinColumn(name = "idOp", referencedColumnName = "id")}, inverseJoinColumns = {
#JoinColumn(name = "idBad", referencedColumnName = "id")})
#ManyToMany(fetch = FetchType.LAZY)
private List<BadgePoint> badgePointList;
#ManyToMany(mappedBy = "operatorList", fetch = FetchType.LAZY)
private List<Zone> zoneList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "operator", fetch = FetchType.LAZY)
private List<TimePass> timePassList;
public Operator() {
}
public Operator(Long id) {
this.id = id;
}
public Operator(Long id, String operatorFName, String operatorLName) {
this.id = id;
this.operatorFName = operatorFName;
this.operatorLName = operatorLName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getOperatorFName() {
return operatorFName;
}
public void setOperatorFName(String operatorFName) {
this.operatorFName = operatorFName;
}
public String getOperatorLName() {
return operatorLName;
}
public void setOperatorLName(String operatorLName) {
this.operatorLName = operatorLName;
}
#XmlTransient
public List<BadgePoint> getBadgePointList() {
return badgePointList;
}
public void setBadgePointList(List<BadgePoint> badgePointList) {
this.badgePointList = badgePointList;
}
#XmlTransient
public List<Zone> getZoneList() {
return zoneList;
}
public void setZoneList(List<Zone> zoneList) {
this.zoneList = zoneList;
}
#XmlTransient
public List<TimePass> getTimePassList() {
return timePassList;
}
public void setTimePassList(List<TimePass> timePassList) {
this.timePassList = timePassList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Operator)) {
return false;
}
Operator other = (Operator) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.rest.Operator[ id=" + id + " ]";
}
}
I added an interface (repository) implementing JpaRepository:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.rest.repository;
import com.rest.model.Operator;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
/**
*
* #author gate11
*/
public interface OperatorRepository extends JpaRepository<Operator, Long>{
#Override
List<Operator> findAll();
}
And as needed, also a controller for the class Operator:
package com.rest.rest;
import com.rest.model.Operator;
import com.rest.service.OperatorService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
public class OperatorController {
#Autowired
private OperatorService operatorService;
#CrossOrigin
#RequestMapping(method = GET, value = "/operator/all")
public List<Operator> loadAll() {
return this.operatorService.findAll();
}
}
The interface service:
package com.rest.service;
import com.rest.model.Operator;
import java.util.List;
/**
*
* #author gate11
*/
public interface OperatorService {
List<Operator> findAll();
}
The service Implement also:
package com.rest.serviceImp;
import com.rest.model.Operator;
import com.rest.repository.OperatorRepository;
import com.rest.service.OperatorService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* #author gate11
*/
#Service
public class OperatorServiceImp implements OperatorService{
#Autowired
private OperatorRepository operatorRepository;
#Override
public List<Operator> findAll() {
List<Operator> operator = operatorRepository.findAll();
return operator;
}
}
When I launch the application, the log:
2018-03-05 14:34:47.427 INFO 10768 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2018-03-05 14:34:47.565 INFO 10768 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: Ant [pattern='/h2-console/**'], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#183bb809, org.springframework.security.web.context.SecurityContextPersistenceFilter#593fdbbe, org.springframework.security.web.header.HeaderWriterFilter#2d784ff4, org.springframework.security.web.authentication.logout.LogoutFilter#55ef8d65, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#3ba7a547, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#12e1efcb, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#57449117, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#5cba96fc, org.springframework.security.web.session.SessionManagementFilter#5403d62a, org.springframework.security.web.access.ExceptionTranslationFilter#4817a878, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#36126980]
2018-03-05 14:34:47.573 INFO 10768 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/**']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#70c855ab, org.springframework.security.web.context.SecurityContextPersistenceFilter#1eef0aa6, org.springframework.security.web.header.HeaderWriterFilter#537d0675, org.springframework.security.web.authentication.logout.LogoutFilter#7d1011c1, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#1b4c8eff, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#73c2d36e, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#48372dcd, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#3cfcbfa3, org.springframework.security.web.session.SessionManagementFilter#4befcfad, org.springframework.security.web.access.ExceptionTranslationFilter#4ed4729f, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#dffb1e0]
2018-03-05 14:34:47.807 INFO 10768 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2018-03-05 14:34:47.900 INFO 10768 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-03-05 14:34:48.000 INFO 10768 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-03-05 14:34:48.008 INFO 10768 --- [ restartedMain] com.rest.Application : Started Application in 10.365 seconds (JVM running for 11.067)
2018-03-05 14:42:28.257 INFO 10768 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-03-05 14:42:28.257 INFO 10768 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-03-05 14:42:28.279 INFO 10768 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 21 ms
Then, I should go to localhost:8080/api/operator/all to get the list of operator as I used to do, but it's asking me to use a username password, I tried everything from db user (root, root) but doesn't work.
I don't even have a connexion page in the application.
enter image description here
If you have any idea, please feel free to suggest, I'm using a Mac as you see.
Thanks.

Related

I can't to see my web page in spring [spring]

I'm new using this framework, I'm tryng to deploy a web with a hibernate connection, I created a .xml config file to connect to PostgreSQL.
But the logs shows this error:
2020-11-14T22:32:28.610246+00:00 heroku[router]: at=info method=GET path="/"
host=gstlabs.herokuapp.com request_id=978ecfdc-917f-41a0-8867-8cc55b73def1 fwd="190.84.149.124" dyno=web.1 connect=2ms service=211ms status=500 bytes=610 protocol=https
2020-11-14T23:04:34.213061+00:00 heroku[web.1]: Idling
2020-11-14T23:04:34.215664+00:00 heroku[web.1]: State changed from up to down
2020-11-14T23:04:35.167671+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2020-11-14T23:04:35.279279+00:00 app[web.1]: 2020-11-14 23:04:35.278 INFO 4 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-11-14T23:04:35.279712+00:00 app[web.1]: 2020-11-14 23:04:35.279 WARN 4 --- [extShutdownHook] o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy method failed on bean with name 'entityManagerFactory': org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.example.core.models.Projects.technologies in com.example.core.models.Technologies.projects
2020-11-14T23:04:35.280073+00:00 app[web.1]: 2020-11-14 23:04:35.279 INFO 4 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2020-11-14T23:04:35.282600+00:00 app[web.1]: 2020-11-14 23:04:35.282 INFO 4 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2020-11-14T23:04:35.325392+00:00 app[web.1]: 2020-11-14 23:04:35.325 INFO 4 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
2020-11-14T23:04:35.426750+00:00 heroku[web.1]: Process exited with status 143
There are my Classes:
[Technologies]
package com.example.core.models;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="technologies")
public class Technologies {
#Id
#Column(name="id")
private int id;
#Column(name="name")
private String name;
public Technologies() {
}
public Technologies(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Technologies [id=" + id + ", name=" + name + "]";
}
#ManyToMany(mappedBy="technologies")
private Set<Projects> projects = new HashSet<>();
public Set<Projects> getProjects() {
return projects;
}
public void setProjects(Set<Projects> projects) {
this.projects = projects;
}
}
[Projects]
package com.example.core.models;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="projects")
public class Projects {
#Id
#Column(name="id")
private int id;
#Column(name="photo")
private String photo;
#Column(name="link")
private String link;
public Projects() {
}
public Projects(String photo, String link) {
this.photo = photo;
this.link = link;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
#Override
public String toString() {
return "Projects [id=" + id + ", photo=" + photo + ", link=" + link + "]";
}
#ManyToMany(cascade= {CascadeType.ALL})
#JoinTable(
name="projects_has_technologies",
joinColumns=#JoinColumn(name="project_id"),
inverseJoinColumns=#JoinColumn(name="technology_id")
)
Set<Technologies> tecnologies = new HashSet<>();
#ManyToMany(mappedBy="projects")
private Set<Profiles> profiles = new HashSet<>();
public Set<Technologies> getTecnologies() {
return tecnologies;
}
public void setTecnologies(Set<Technologies> tecnologies) {
this.tecnologies = tecnologies;
}
public Set<Profiles> getProfiles() {
return profiles;
}
public void setProfiles(Set<Profiles> profiles) {
this.profiles = profiles;
}
}
There are some code that are some at my clases in this proyect the other intermedial clases are similar, I'm trynt in this moment insert some objects to the database.
Thanks to your help in advance.
Have you tried to add a Configuration Class in your project for example
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories( basePackages = "your repository package" )
#EntityScan( basePackages = {"your entity package1","your entity package2"}
public class TransactionConfiguration {}
This will help you to find your entity classes in the project.

org.springframework.beans.factory.UnsatisfiedDependencyException: error after adding new repository

Hello im trying to work on a project first of all it was all smooth when i worked on a single model as you see below "Student"
StudentController
package net.springboot.javaguides.controller;
import javax.validation.Valid;
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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import net.springboot.javaguides.entity.Student;
import net.springboot.javaguides.repository.StudentRepository;
#Controller
#RequestMapping("/students/")
public class StudentController {
#Autowired
private StudentRepository studentRepository;
#GetMapping("showForm")
public String showStudentForm(Student student) {
return "student/add-student";
}
#GetMapping("list")
public String students(Model model) {
model.addAttribute("students", this.studentRepository.findAll());
return "student/index";
}
#PostMapping("add")
public String addStudent(#Valid Student student, BindingResult result, Model model) {
if(result.hasErrors()) {
return "student/add-student";
}
this.studentRepository.save(student);
return "redirect:list";
}
#GetMapping("edit/{id}")
public String showUpdateForm(#PathVariable ("id") long id, Model model) {
Student student = this.studentRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid student id : " + id));
model.addAttribute("student", student);
return "student/update-student";
}
#PostMapping("update/{id}")
public String updateStudent(#PathVariable("id") long id, #Valid Student student, BindingResult result, Model model) {
if(result.hasErrors()) {
student.setId(id);
return "student/update-student";
}
// update student
studentRepository.save(student);
// get all students ( with update)
model.addAttribute("students", this.studentRepository.findAll());
return "student/index";
}
#GetMapping("delete/{id}")
public String deleteStudent(#PathVariable ("id") long id, Model model) {
Student student = this.studentRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid student id : " + id));
this.studentRepository.delete(student);
model.addAttribute("students", this.studentRepository.findAll());
return "student/index";
}
}
StudentEntity
package net.springboot.javaguides.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "students")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "name")
private String name;
#Column(name = "email")
private String email;
#Column(name = "phone_no")
private long phoneNo;
public Student() {
super();
}
public Student(String name, String email) {
super();
this.name = name;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(long phoneNo) {
this.phoneNo = phoneNo;
}
}
StudentRepository
package net.springboot.javaguides.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.springboot.javaguides.entity.Student;
#Repository
public interface StudentRepository extends JpaRepository<Student, Long>{
List<Student> findByName(String name);
}
and now im trying to add some new model as you see below but im having error from it :
CourseController
package net.springboot.javaguides.controller;
import javax.validation.Valid;
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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import net.springboot.javaguides.entity.Course;
import net.springboot.javaguides.repository.CourseRepository;
#Controller
#RequestMapping("/courses/")
public class CourseController {
#Autowired
private CourseRepository courseRepository;
#GetMapping("showForm")
public String showCourseForm(Course course) {
return "add-course";
}
#GetMapping("list")
public String courses(Model model) {
model.addAttribute("courses", this.courseRepository.findAll());
return "index";
}
#PostMapping("add")
public String addCourse(#Valid Course course, BindingResult result, Model model) {
if(result.hasErrors()) {
return "add-course";
}
this.courseRepository.save(course);
return "redirect:list";
}
#GetMapping("edit/{id}")
public String showUpdateForm(#PathVariable ("id") long id, Model model) {
Course course = this.courseRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid course id : " + id));
model.addAttribute("course", course);
return "update-course";
}
#PostMapping("update/{id}")
public String updateCourse(#PathVariable("id") long id, #Valid Course course, BindingResult result, Model model) {
if(result.hasErrors()) {
course.setId(id);
return "update-course";
}
// update course
courseRepository.save(course);
// get all courses ( with update)
model.addAttribute("courses", this.courseRepository.findAll());
return "index";
}
#GetMapping("delete/{id}")
public String deleteCourse(#PathVariable ("id") long id, Model model) {
Course course = this.courseRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid course id : " + id));
this.courseRepository.delete(course);
model.addAttribute("courses", this.courseRepository.findAll());
return "index";
}
}
CourseEntity
package net.springboot.javaguides.entity;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Courses")
public class Course {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "cours_name")
private String cours_name;
#Column(name = "date_debut")
private Date date_debut;
#Column(name = "date_fin")
private Date date_fin;
#Column(name = "enseignant")
private String enseignant;
#Column(name = "type_cours")
private String type_cours;
#Column(name = "filliere")
private String filliere;
public Course() {
super();
}
public Course(String cours_name, Date date_debut, Date date_fin, String enseignant, String type_cours,
String filliere) {
super();
this.cours_name = cours_name;
this.date_debut = date_debut;
this.date_fin = date_fin;
this.enseignant = enseignant;
this.type_cours = type_cours;
this.filliere = filliere;
}
public Long getId() {
return id;
}
public String getCours_name() {
return cours_name;
}
public void setCours_name(String cours_name) {
this.cours_name = cours_name;
}
public Date getDate_debut() {
return date_debut;
}
public void setDate_debut(Date date_debut) {
this.date_debut = date_debut;
}
public Date getDate_fin() {
return date_fin;
}
public void setDate_fin(Date date_fin) {
this.date_fin = date_fin;
}
public String getEnseignant() {
return enseignant;
}
public void setEnseignant(String enseignant) {
this.enseignant = enseignant;
}
public String getType_cours() {
return type_cours;
}
public void setType_cours(String type_cours) {
this.type_cours = type_cours;
}
public String getfilliere() {
return filliere;
}
public void setfilliere(String filliere) {
this.filliere = filliere;
}
public void setId(Long id) {
this.id = id;
}
}
**
CourseRepository
**
package net.springboot.javaguides.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.springboot.javaguides.entity.Course;
#Repository
public interface CourseRepository extends JpaRepository<Course, Long>{
List<Course> findByName(String cours_name);
}
but im having this error
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.0.RELEASE)
2020-08-27 13:44:03.876 INFO 9188 --- [ restartedMain] s.j.SpringbootThymeleafWebAppApplication : Starting SpringbootThymeleafWebAppApplication on DESKTOP-5D7IMCJ with PID 9188 (C:\Users\yassi\Desktop\workspacenew\springboot-thymeleaf-web-app-master\target\classes started by yassi in C:\Users\yassi\Desktop\workspacenew\springboot-thymeleaf-web-app-master)
2020-08-27 13:44:03.880 INFO 9188 --- [ restartedMain] s.j.SpringbootThymeleafWebAppApplication : No active profile set, falling back to default profiles: default
2020-08-27 13:44:03.941 INFO 9188 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-08-27 13:44:03.941 INFO 9188 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-08-27 13:44:04.881 INFO 9188 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2020-08-27 13:44:04.957 INFO 9188 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 68ms. Found 2 repository interfaces.
2020-08-27 13:44:05.415 INFO 9188 --- [ restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$97fbb782] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-08-27 13:44:05.849 INFO 9188 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-08-27 13:44:05.868 INFO 9188 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-27 13:44:05.868 INFO 9188 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/9.0.12
2020-08-27 13:44:05.876 INFO 9188 --- [ restartedMain] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_221\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_221/bin/server;C:/Program Files/Java/jre1.8.0_221/bin;C:/Program Files/Java/jre1.8.0_221/lib/amd64;C:\oraclexe\app\oracle\product\11.2.0\server\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files\MySQL\MySQL Server 5.1\bin;C:\Users\yassi\AppData\Local\Microsoft\WindowsApps;;C:\Users\yassi\AppData\Local\Programs\Microsoft VS Code\bin;D:\eclipse;;.]
2020-08-27 13:44:05.990 INFO 9188 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-27 13:44:05.990 INFO 9188 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2049 ms
2020-08-27 13:44:06.025 INFO 9188 --- [ restartedMain] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2020-08-27 13:44:06.031 INFO 9188 --- [ restartedMain] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2020-08-27 13:44:06.031 INFO 9188 --- [ restartedMain] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2020-08-27 13:44:06.031 INFO 9188 --- [ restartedMain] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'formContentFilter' to: [/*]
2020-08-27 13:44:06.031 INFO 9188 --- [ restartedMain] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2020-08-27 13:44:06.203 INFO 9188 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-08-27 13:44:06.332 INFO 9188 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2020-08-27 13:44:06.388 INFO 9188 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2020-08-27 13:44:06.630 INFO 9188 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final}
2020-08-27 13:44:06.632 INFO 9188 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2020-08-27 13:44:06.776 INFO 9188 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2020-08-27 13:44:06.917 INFO 9188 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2020-08-27 13:44:07.829 INFO 9188 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-08-27 13:44:07.871 INFO 9188 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-08-27 13:44:08.146 WARN 9188 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'courseController': Unsatisfied dependency expressed through field 'courseRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courseRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List net.springboot.javaguides.repository.CourseRepository.findByName(java.lang.String)! No property name found for type Course!
The log says the problem already! .repository.CourseRepository.findByName(java.lang.String)! No property name found for type Course! Your Course entity doesn't have a property called name, it's called cours_name. Change the cours_name in your Course entity to name or change the name of the method in CourseRepository!
Try adding #EnableJpaRepositories(packages) on top of your main class.
i had an same issue, i handled with adding #EntityScan or #EnableJpaRepositories(packages)

methods in an ejb session bean for an entity dont work in a spring MVC project

I created a maven entreprise application project, in the ejb module i put my entities in a package and i generated my session beans in an other package and i deployed my ejb module in glassfish,in the web module i added dependencies of spring and I created a controller that search the session bean and call the methode find all() but it doesnt get my objects stored in database, what should i do?
Category entity
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author DELL
*/
#Entity
#Table(name = "categorie")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Categorie.findAll", query = "SELECT c FROM Categorie c"),
#NamedQuery(name = "Categorie.findByIdCategorie", query = "SELECT c FROM Categorie c WHERE c.idCategorie = :idCategorie"),
#NamedQuery(name = "Categorie.findByDescription", query = "SELECT c FROM Categorie c WHERE c.description = :description"),
#NamedQuery(name = "Categorie.findByName", query = "SELECT c FROM Categorie c WHERE c.name = :name"),
#NamedQuery(name = "Categorie.findByNomPhoto", query = "SELECT c FROM Categorie c WHERE c.nomPhoto = :nomPhoto")})
public class Categorie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idCategorie")
private Integer idCategorie;
#Size(max = 255)
#Column(name = "description")
private String description;
#Size(max = 20)
#Column(name = "name")
private String name;
#Size(max = 255)
#Column(name = "nomPhoto")
private String nomPhoto;
#Lob
#Column(name = "photo")
private byte[] photo;
#OneToMany(mappedBy = "idCategorie")
private List<Produit> produitList;
public Categorie() {
}
public Categorie(Integer idCategorie) {
this.idCategorie = idCategorie;
}
public Integer getIdCategorie() {
return idCategorie;
}
public void setIdCategorie(Integer idCategorie) {
this.idCategorie = idCategorie;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNomPhoto() {
return nomPhoto;
}
public void setNomPhoto(String nomPhoto) {
this.nomPhoto = nomPhoto;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
#XmlTransient
public List<Produit> getProduitList() {
return produitList;
}
public void setProduitList(List<Produit> produitList) {
this.produitList = produitList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idCategorie != null ? idCategorie.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Categorie)) {
return false;
}
Categorie other = (Categorie) object;
if ((this.idCategorie == null && other.idCategorie != null) || (this.idCategorie != null && !this.idCategorie.equals(other.idCategorie))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.mycompany.entities.Categorie[ idCategorie=" + idCategorie + " ]";
}
}
AbstractFacade
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dao;
import java.util.List;
import javax.persistence.EntityManager;
/**
*
* #author DELL
*/
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
CategorieFacade
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dao;
import com.mycompany.entities.Categorie;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author DELL
*/
#Stateless
public class CategorieFacade extends AbstractFacade<Categorie> implements CategorieFacadeLocal {
#PersistenceContext(unitName = "com.mycompany_ProjetCommerce-ejb_ejb_1.0-SNAPSHOTPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public CategorieFacade() {
super(Categorie.class);
}
}
CategorieFacadeLocal
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.dao;
import com.mycompany.entities.Categorie;
import java.util.List;
import javax.ejb.Local;
/**
*
* #author DELL
*/
#Local
public interface CategorieFacadeLocal {
void create(Categorie categorie);
void edit(Categorie categorie);
void remove(Categorie categorie);
Categorie find(Object id);
List<Categorie> findAll();
List<Categorie> findRange(int[] range);
int count();
}
CategorieController
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.controlleur;
import com.mycompany.dao.CategorieFacadeLocal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.springframework.stereotype.*;
import org.springframework.ui.*;
import org.springframework.web.bind.annotation.*;
#Controller
#RequestMapping("categorie")
public class CategorieController {
CategorieFacadeLocal categorieFacade = lookupCategorieFacadeLocal();
#RequestMapping(method = RequestMethod.GET)
public String index(ModelMap modelmap){
modelmap.put("listeCategorie", categorieFacade.findAll());
return "index";
}
private CategorieFacadeLocal lookupCategorieFacadeLocal() {
try {
Context c = new InitialContext();
return (CategorieFacadeLocal) c.lookup("java:global/com.mycompany_ProjetCommerce-ear_ear_1.0-SNAPSHOT/com.mycompany_ProjetCommerce-ejb_ejb_1.0-SNAPSHOT/CategorieFacade!com.mycompany.dao.CategorieFacadeLocal");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}

Spring Test DBUnit: Unable to load dataset from file

I'm trying to use Spring Test DBUnit for running an integration test that checks if a DAO's services are running correctly. For two similar entities, I was able to create tests that run OK, but for this particular entity, the test can't run properly.
The test will be ignored, and the only Exception I will see in the console is:
java.lang.IllegalArgumentException: Unable to load dataset from "data/offline_message.xml" using class com.github.springtestdbunit.dataset.FlatXmlDataSetLoader
Here are the relevant files. XML file:
<dataset>
<mp_account id="1" auth_hash="ted.mosby" first_name="Ted" last_name="Mosby" credential="EMAIL" transport_session="someTransportSession"/>
<mp_account id="2" auth_hash="lily.aldrin" first_name="Lily" last_name="Aldrin" credential="MEH" transport_session="someTransportSession"/>
<mp_message id="1" recipient_account_id="1" sender_account_id="2"/>
</dataset>
Test class that is failing:
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.somecompany.messaging.domain.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Date;
import java.util.List;
#DatabaseSetup("data/message.xml")
public class MessageDaoTest extends AbstractDaoTest<Message> {
private static final Long ACCOUNT_ID = 1L;
public static final long DATE_LONG = 1431018764154L;
private static final Date LAST_UPDATE_TS = new Date(DATE_LONG);
#Autowired
MessageDao MessageDao;
#BeforeMethod
public void setUp() throws Exception {
this.setDao(MessageDao);
}
#Test
#Transactional
public void testFindMessages() throws Exception {
List<Message> Messages = this.MessageDao.findMessages(ACCOUNT_ID, LAST_UPDATE_TS);
Assert.assertNotNull(Messages);
Assert.assertEquals(Messages.size(), 1);
}
}
Abstract test class, that extends from TestNG's class:
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class })
#ContextConfiguration(locations = { "classpath:test-context.xml" })
public class AbstractDaoTest <T> extends AbstractTestNGSpringContextTests {
private GenericDao<T> dao;
#Transactional
public T create(T t){
return dao.create(t);
}
#Transactional
public void delete(Object id){
dao.delete(id);
}
#Transactional
public T find(Object id){
return dao.find(id);
}
#Transactional
public T update(T t){
return dao.update(t);
}
public void setDao(GenericDao<T> dao) {
this.dao = dao;
}
}
Finally, the Entity:
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import javax.persistence.*;
#NamedQueries({
#NamedQuery(
name = "findMessagesQuery",
query = "select om from Message om where om.recipientAccount.id=:accountId " +
"and om.lastUpdatedTs>:time and om.lastUpdatedTs+om.expirationPeriod>:now " +
"order by om.lastUpdatedTs asc"
),
#NamedQuery(
name = "findExpiredMessagesQuery",
query = "select om from Message om where om.lastUpdatedTs+om.expirationPeriod<:now"
)
})
#Entity
#Table(name="mp_message")
public class Message extends AbstractModel {
#JoinColumn(name="recipient_account_id", updatable = false)
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Account recipientAccount;
#JoinColumn(name="sender_account_id", updatable = false)
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Account senderAccount;
#Column(name="message_body", length=2048)
private String messageBody;
#Column(name="expiration_period")
private Long expirationPeriod;
// Getters, setters, etc excluded for brevity
}
Just a sidenote: I have "obscured" the Entity name (dammned lawyers!), so there could be some small name mistakes. Please bear with me on this ;)
If you need some additional details, please let me know.
Thanks in advance
try to add classpath: before your path, so:
#DatabaseSetup("classpath:data/message.xml")
Just do this, it works. the relative path can be used.
#DatabaseSetup("/data/message.xml"")

generalized java service using hibernate envers to audit changes done by user in database in web application

public class App
{
public static void main( String[] args )
{
//test insert
tx = session.beginTransaction();
System.out.println("Maven + Hibernate + MySQL");
// Session session = HibernateUtil.getSessionFactory().openSession();
//session.beginTransaction();
Stock stock = new Stock();
stock.setStockCode("7000");
stock.setStockName("z");
session.saveOrUpdate(stock);
}
Stock.java
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import com.warp.intercept.*;
/**
* Stock generated by hbm2java
*/
#Entity
#Table(name = "stock", catalog = "mkyong", uniqueConstraints = {
#UniqueConstraint(columnNames = "STOCK_NAME"),
#UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements java.io.Serializable, IAuditLog {
private Integer stockId;
private String stockCode;
private String stockName;
public Stock() {
}
public Stock(String stockCode, String stockName) {
this.stockCode = stockCode;
this.stockName = stockName;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "STOCK_ID", unique = true, nullable = false)
public Integer getStockId() {
return this.stockId;
}
public void setStockId(Integer stockId) {
this.stockId = stockId;
}
#Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
public String getStockCode() {
return this.stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
#Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
public String getStockName() {
return this.stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
I have a java web application, I want to create audit logs in database for all the database changes like(column changed, value changed in column, userid, timestamp and some other fields). I want to create a generalized service which has methods exposed for such operations and I can access them from any other component in the application. As far as I have read, this can be done through hibernate envers or Spring AOP. Can you please suggest and provde me with an example which I can utilize to extend it further.
P.S. : I don't want to use trigger based logging for auditing database changes
Suppose this is my entiity stock; I am performing some simple save operations on the stock thru hibernate. Suppose, I have a main method and I perform below mentioned operation
Well, I am not a Spring or Hibernate user, so I do not know what exactly you need to capture. But if it is just the setters of any #Entity-annotated class, the whole thing would basically look like this:
Driver application:
package de.scrum_master.app;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class Application {
public static void main(String[] args) {
System.out.println("Maven + Hibernate + MySQL");
// Session session = HibernateUtil.getSessionFactory().openSession();
// Transaction tx = session.beginTransaction();
Stock stock = new Stock();
stock.setStockCode("7000");
stock.setStockName("z");
// session.saveOrUpdate(stock);
}
}
Auditing aspect:
package de.scrum_master.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
#Aspect
public class DBAuditAspect {
#Before("execution(public void set*(*)) && #target(javax.persistence.Entity) && args(setterArgument)")
public void entitySetterExecution(Object setterArgument, JoinPoint thisJoinPoint) {
System.out.println(thisJoinPoint + " - " + setterArgument);
}
}
Console output:
Maven + Hibernate + MySQL
execution(void de.scrum_master.app.Stock.setStockCode(String)) - 7000
execution(void de.scrum_master.app.Stock.setStockName(String)) - z
The more general question of how to set up and use Spring AOP is explained in the documentation, chapter 9. Aspect Oriented Programming with Spring.

Resources