Spring Data fills #LastModifiedDate by not #CreatedDate - java

I have following Spring Boot sample application.
The crazy thing is if I add #EnableMongoAuditing annotation on SampleApplication bean, lastModifiedDate would be filled by createDate would not. Why is that? I searched the web and many people had problems on emptying createDate during an update, but I don't have an update.
Document class:
#Document
public class SampleBean implements Persistable<String> {
#Id
public String id;
#CreatedDate
public LocalDateTime createDate;
#LastModifiedDate
public LocalDateTime lastModifiedDate;
public String name;
#Override
public String getId() {
return id;
}
#Override
public boolean isNew() {
return id != null;
}
}
Repository Interface:
#Repository
public interface SampleBeanRepository extends MongoRepository<SampleBean, String> {
}
Rest Controller:
#RestController
public class WebService {
#Autowired
private SampleBeanRepository repository;
#RequestMapping("/insert")
public String insert() {
SampleBean sampleBean = new SampleBean();
sampleBean.name = "Prefix" + new Random().nextInt(1000);
repository.insert(sampleBean);
return "done";
}
#RequestMapping("/")
public Collection<SampleBean> home() {
return repository.findAll();
}
}
Application Config:
#SpringBootApplication
#EnableMongoAuditing
public class ApplicationConfig {
public static void main(String[] args) {
SpringApplication.run(ApplicationConfig.class, args);
}
}

Your isNew() strategy is the culprit here. Since you have set condition as id != null. Everytime your SampleBean is created there will be no id set as per your code snippet, the isNew() method will return as false hence only LastModifiedDate will be set by the framework. Either change the isNew() method condition to return id == null; or just don't implement Persistable interface whatever default strategy for isNew will be picked.

Related

How to set up database connection in r2dbc?

How to set up a PostgreSQL database connection in r2dbc Spring boot project?
I have tried the below configuration, it connects to the database but it's not returning any values
#Configuration
#EnableR2dbcRepositories
public class DatabaseConfig extends AbstractR2dbcConfiguration {
#Override
public ConnectionFactory connectionFactory() {
return ConnectionFactories.get("r2dbc:postgresql://localhost:5432/sample");
}
/*#Override
public ConnectionFactory connectionFactory() {
return ConnectionFactories.get(new PostgresqlConnectionFactory(
PostgresqlConnectionConfiguration.builder()
.host("localhost")
.port(5432)
.username("postgres")
.password("thirumal")
.database("sample")
.build()););
}*/
}
application.properties
spring.r2dbc.url=r2dbc:postgresql://localhost:5432/sample
spring.r2dbc.username=postgres
spring.r2dbc.password=thirumal
spring.r2dbc.pool.enabled=true
Model
#Data#NoArgsConstructor#AllArgsConstructor#Getter#Setter
#ToString
#Table("public.test")
public class Test implements Serializable{
/**
*
*/
private static final long serialVersionUID = 4205798689305488147L;
#Id//#Column("id")
private Long id;
private String name;
}
Repository
public interface TestRepository extends ReactiveCrudRepository<Test, Long> {
}
REST CONTROLLER:
#GetMapping("/test")
public Mono<Test> test() {
testRepository.findById(3L).subscribe(v->System.out.println("Value: " + v.toString()));
return testRepository.findById(3L);
}
It prints the output in the console but in the JSON, I get only empty braces {}
What is the correct way to configure? Any other configuration is required?
I found the problem. It's Lombok library, I didn't install it in eclipse.
When I created the getter and setter method manually it worked.
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;
}
Then, I set up the lombok and used #getter and #setter and it worked.
This configuration works for me, but I use the DatabaseClient instead of the R2dbcRepositories to query the data:
#Configuration
public class DatabaseConfiguration extends AbstractR2dbcConfiguration {
#Override
#Bean
public ConnectionFactory connectionFactory() {
return new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration.builder()
.host("localhost")
.port(5432)
.username("username")
.password("password")
.database("mydb")
.build());
}
}
Then in the repository:
#Repository
public class MyRepository {
#Autowired
private DatabaseClient client;
public Flux<String> getString() {
....
}
}
UPDATE:
If it's connect to the database probably your configuration is right, can you share also the code used to get the data?
It's possible that you are getting the result as Mono or Flux, but not reading from it (try with subscribe()).
Mono<String> mono = db.getData();
mono.subscribe(value -> System.out.println(value));

Repository related methods return only null values

I have a Spring Boot application in which I have created an entity, a repository and a service.
I save entities in the database via transactions and everything works fine, my database is populated as I would expect. Also, I should mention that my database is created in PHPMyAdmin.
I also created a repository in order to fetch some data from the database by extending the Crud Repository. I also have a service which stores the methods that call the repository.
Though, none of the methods I have return anything ( my database is not empty ) and I do not know why. I have also tried adding #EnableJpaRepositories and #ComponentScan for the entity, but this did not work. Below are my classes:
The entity ( I will not put all the getters and setters here) :
#Entity
#Table(name = "matches", schema = "tennis", catalog = "")
public class MatchesEntity {
private int id;
private String namePlayer1;
private String namePlayer2;
private int setsPlayer1;
private int setsPlayer2;
private String odd1;
private String odd2;
private String competition;
private String surface;
private String status;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "Name_player1")
public String getNamePlayer1() {
return namePlayer1;
}
public void setNamePlayer1(String namePlayer1) {
this.namePlayer1 = namePlayer1;
}
#Basic
#Column(name = "Name_player2")
public String getNamePlayer2() {
return namePlayer2;
}
// other getter & setters
}
The repository:
#Repository
public interface MatchesRepository extends CrudRepository<MatchesEntity,
Integer> {
List<MatchesEntity> getAllBySurface(String surface);
}
The service:
#Service
public class MatchesService {
#Autowired
MatchesRepository matchesRepository;
public int countMatchesOnHard() {
return matchesRepository.getAllBySurface("hard").size();
}
public MatchesEntity findMatchById() {
return matchesRepository.findById(2378).get();
}
}
The main class:
#SpringBootApplication
#EnableJpaRepositories(basePackageClasses={MatchesRepository.class})
#EntityScan(basePackageClasses=MatchesEntity.class)
public class PicksApplication {
#Autowired
static MatchesService matchesService;
public static void main(String[] args) {
MatchesEntity matchesEntity = matchesService.findMatchById();
int numberOfMatchesOnHard = matchesService.countMatchesOnHard();
System.out.println(numberOfMatchesOnHard);
}
}
Any method I try which is repository related returns null.
Can anyone help me with a suggestion ?
Your main class PicksApplication is troublesome. The main method must trigger SpringApplication.run for the spring boot to initialize itself & the context for autowires to work. You are breaking all that within your code. You can utilize CommandLineRunner and add your code in run() method.
Like this;
#SpringBootApplication
public class PicksApplication implements CommandLineRunner {
#Autowired
private MatchesService matchesService;
public static void main(String[] args) {
SpringApplication.run(PicksApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
MatchesEntity matchesEntity = matchesService.findMatchById();
int numberOfMatchesOnHard = matchesService.countMatchesOnHard();
System.out.println(numberOfMatchesOnHard);
}
}
then it ought to work, rest of the code looks OK

Hibernate: Getting result using a specific field

I've been following a lot of tutorial on how to get a list of result by referencing a specific column in the table.
I have this table.
I want to get the list of result with a plan_code "TEST123"
This is my code:
PlanRepository.java
public interface PlanCoverageRepository extends CrudRepository<PlanCoverage, Long> {
List<PlanCoverage> findAllByPlan_code(String plan_code);
}
PlanCoverageService.java
public interface PlanCoverageService {
public List<PlanCoverage> getAllPlanCoverageByPlanCode(String plan_code);
}
PlanCoverageServiceImpl.java
#Service
#Transactional
public class PlanCoverageServiceImpl implements PlanCoverageService {
#Override
public List<PlanCoverage> getAllPlanCoverageByPlanCode(String plan_code) {
return (List<PlanCoverage>) planCoverageRepository.findAllByPlan_code(plan_code);
}
}
PlanCoverageController.java
#Controller
#RequestMapping(value="/admin")
public class PlanCoverageController {
#Autowired
PlanCoverageService planCoverageService;
#RequestMapping(value="/Test/{plan_code}", method=RequestMethod.GET)
public ModelAndView test(#PathVariable String plan_code) {
ModelAndView model = new ModelAndView();
PlanCoverage planCoverage = (PlanCoverage) planCoverageService.getAllPlanCoverageByPlanCode(plan_code);
model.addObject("planCoverageForm",planCoverage);
model.setViewName("plan_coverage_form");
return model;
}
}
PlanCoverage.java
#Entity
#Table(name="plan_coverage")
public class PlanCoverage {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private long coverage_id;
#Column(name="plan_code")
private String plan_code;
#Column(name="coverage_description")
private String coverage_description;
/..getters and setters
#ManyToOne()
#JoinColumn(name="plan_code", referencedColumnName = "plan_code",insertable=false, updatable=false)
private Plan plan;
public Plan getPlan() {
return plan;
}
public void setPlan(Plan plan) {
this.plan = plan;
}
}
Please help me. I've been stuck with these for a few days and non of the tutorials seems to work on me. Thank you so much!!
You have messed up with the convention that spring boot is using to compose query methods. The case of the fields in the entity should follow the lower camel-case scheme, like so:
#Column(name="plan_code")
private String planCode;
and then the query method in PlanCoverageRepository should be:
List<PlanCoverage> findAllByPlanCode(String planCode);

Spring data rest validation for PUT and PATCH running after DB update

I have a SDR project and I am successfully validating the user entity for POST request but as soon as I update an existing entity using either PATCH or PUT the DB is updated BEFORE the validation is executed (the validator is being executed and error is returned but the DB is being updated anyway).
Do I need to setup a separate config for update ? Am I missing an extra step for that?
Entity
#Entity
#JsonIgnoreProperties(ignoreUnknown = true)
public class Member {
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "member_id_gen")
#SequenceGenerator(name = "member_id_gen", sequenceName = "member_id_seq")
#Id
#JsonIgnore
private long id;
#Version
private Integer version;
#NotNull
protected String firstName;
#NotNull
protected String lastName;
#Valid
protected String email;
}
Repository
#RepositoryRestResource(collectionResourceRel = "members", path = "member")
public interface MemberRepository extends PagingAndSortingRepository<Member, Long> {
public Member findByFirstName(String firstName);
public Member findByLastName(String lastName);
}
Validator
#Component
public class BeforeSaveMemberValidator implements Validator {
public BeforeSaveMemberValidator() {}
private String EMAIL_REGEX = "^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";
#Override
public boolean supports(Class<?> clazz) {
return Member.class.equals(clazz);
}
#Override
public void validate(Object target, Errors errors) {
Member member = (Member) target;
if(ObjectUtils.isEmpty(member.getFirstName())) {
errors.rejectValue("firstName", "member.firstName.empty");
}
if(ObjectUtils.isEmpty(member.getLastName())) {
errors.rejectValue("lastName", "member.lastName.empty");
}
if(!ObjectUtils.isEmpty(member.getDni()) && !member.getDni().matches("^[a-zA-Z0-9]*$")) {
errors.rejectValue("dni", "member.dni.invalid");
}
if(!ObjectUtils.isEmpty(member.getEmail()) && !member.getEmail().matches(EMAIL_REGEX)) {
errors.rejectValue("email", "member.email.notValid");
}
}
}
BeforeSave service
#Service
#RepositoryEventHandler(Member.class)
public class MemberService {
#HandleBeforeCreate
#HandleBeforeSave
#Transactional
public void beforeCreate(Member member) {
...
}
}
I think you should rename your validator, for example, to MemberValidator then assign it as described here:
#Override
protected void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener v) {
v.addValidator("beforeCreate", new MemberValidator());
v.addValidator("beforeSave", new MemberValidator());
}
But I suggest you to use Bean validation instead of your custom validators. To use it in SDR project you can inject LocalValidatorFactoryBean, then assign it for 'beforeCreate' and 'beforeSave' events in configureValidatingRepositoryEventListener:
#Configuration
#RequiredArgsConstructor // Lombok annotation
public class RepoRestConfig extends RepositoryRestConfigurerAdapter {
#NonNull private final LocalValidatorFactoryBean validatorFactoryBean;
#Override
public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener v) {
v.addValidator("beforeCreate", validatorFactoryBean);
v.addValidator("beforeSave", validatorFactoryBean);
super.configureValidatingRepositoryEventListener(v);
}
}
In this case your SDR will automatically validate payloads of POST, PUT and PATCH requests for all exposed SDR repositories.
See my example for more details.

Get data from a repository using Spring

Ok so I am new to spring and don't really know how this works. I have been trying a few things and think its close to doing it but not getting any data from the server and giving me this error
Unsatisfied dependency expressed through constructor argument with index 4 of type [jp.co.fusionsystems.dimare.crm.service.impl.MyDataDefaultService]: : Error creating bean with name 'MyDataDefaultService' defined in file
My end point
//mobile data endpoint
#RequestMapping(
value = API_PREFIX + ENDPOINT_MyData + "/getMyData",
method = RequestMethod.GET)
public MyData getMyData() {
return MyDataDefaultService.getData();
}
My Object
public class MyData {
public MyData(final Builder builder) {
videoLink = builder.videoLink;
}
private String videoLink;
public String getVideoLink()
{
return videoLink;
}
public static class Builder
{
private String videoLink = "";
public Builder setVideo(String videoLink)
{
this.videoLink = videoLink;
return this;
}
public MyData build()
{
return new MyData(this);
}
}
#Override
public boolean equals(final Object other) {
return ObjectUtils.equals(this, other);
}
#Override
public int hashCode() {
return ObjectUtils.hashCode(this);
}
#Override
public String toString() {
return ObjectUtils.toString(this);
}
}
The Repository
public classMyServerMyDataRepository implements MyDataRepository{
private finalMyServerMyDataJpaRepository jpaRepository;
private final MyDataConverter MyDataConverter = new MyDataConverter();
#Autowired
publicMyServerMyDataRepository(finalMyServerMyDataJpaRepository jpaRepository) {
this.jpaRepository = Validate.notNull(jpaRepository);
}
#Override
public MyData getData() {
MyDataEntity entity = jpaRepository.findOne((long) 0);
MyData.Builder builder = new MyData.Builder()
.setVideo(entity.getVideoLink());
return builder.build();
}
The DefaultService that gets called by the endpoint
public class MyDataDefaultService {
private static final Logger logger = LoggerFactory.getLogger(NotificationDefaultService.class);
private finalMyServerMyDataRepository repository;
#Autowired
public MyDataDefaultService(MyServerMyDataRepository repository) {
this.repository = Validate.notNull(repository);
}
//Get the data from the server
public MobileData getData()
{
logger.info("Get Mobile Data from the server");
//Get the data from the repository
MobileData mobileData = repository.getData();
return mobileData;
}
}
The Converter
public class MyDataConverter extends AbstractConverter<MyDataEntity, MyData>
{
#Override
public MyData convert(MyDataEntity entity) {
MyData.Builder builder = new MyData.Builder()
.setVideo(entity.getVideoLink());
return builder.build();
}
}
My Entity
#Entity
#Table(name = “myServer”)
public class MyDataEntity extends AbstractEntity{
#Column(name = "video_link", nullable = true)
private String videoLink;
public String getVideoLink() {
return videoLink;
}
public void setVideoLink(final String videoLink) {
this.videoLink = videoLink;
}
}
Thank you for any help with this
Hibernate entity should have default constructor defined and implement Serializable interface as well, assume AbstractEntity matches the requirement. Hibernate won't accept an entity without a primary key so you have to define the one too:
#Entity
#Table(name = “myServer”)
public class MyDataEntity implements Serializable {
#Id
#GeneratedValue
private Long id;
#Column(name = "video_link", nullable = true)
private String videoLink;
public MyDataEntity() {
}
...setters&getters
}
MyData object represents the JSON server response, you can use Jackson annotations to control the result JSON properties:
public class MyDataResponse {
#JsonProperty("video_link")
private String videoLink;
public MyDataResponse() {
}
public MyDataResponse(String videoLink) {
this.videoLink = videoLink;
}
...setters&getters
}
Spring has an awesome project so called Spring Data that provides the JPA repositories, so there's no even the #Repository annotation ever needed:
public class MyDataRepository extends CrudRepository<MyDataEntity, Long> {
}
The Builder class represents the Service layer:
#Service
public class MyDataService {
#Autowired
private MyDataRepository myDataRepository;
public MyDataResponse getMyData(Long id) {
MyDataEntity entity = myDataRepository.findOne(id);
...rest logic, copy necessary data to MyDataResponse
}
}
Then a controller is:
#RestController // #ResponseBody not needed when using like this
public MyDataController {
#Autowired
private MyDataService myDataService;
#RequestMapping("/getMyData") // no need to specify method for GET
public MyDataResponse getMyData(#RequestParam("ID") Long myDataId) {
... validation logic
return myDataService.getMyData(myDataId); // return response
}
}
Now it should work, don't forget to add required dependencies to your classpath.

Categories

Resources