Monday, June 1, 2020

Hibernate ORM (or simply Hibernate) is an object-relational mapping tool for the Java programming language






spring.datasource.url= # JDBC url of the database.


spring.datasource.username= # Login user of the database.

spring.datasource.password= # Login password of the database.

spring.jpa.show-sql=false # Enable logging of SQL statements.

spring.jooq.sql-dialect= # SQLDialect JOOQ used when communicating with the configured datasource. For instance `POSTGRES`

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/notes_app?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username = root
spring.datasource.password = callicoder


## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update


The @GetMapping("/notes") annotation is a short form of @RequestMapping(value="/notes", method=RequestMethod.GET).

1. Get All Notes (GET /api/notes)
// Get All Notes
@GetMapping("/notes")
public List<Note> getAllNotes() {
return noteRepository.findAll();
}

The above method is pretty straightforward. It calls JpaRepository’s findAll() method to retrieve all the notes from the database and returns the entire list.
Also, The @GetMapping("/notes") annotation is a short form of @RequestMapping(value="/notes", method=RequestMethod.GET).
2. Create a new Note (POST /api/notes)
// Create a new Note
@PostMapping("/notes")
public Note createNote(@Valid @RequestBody Note note) {
return noteRepository.save(note);
}

The @RequestBody annotation is used to bind the request body with a method parameter.
The @Valid annotation makes sure that the request body is valid. Remember, we had marked Note’s title and content with @NotBlank annotation in the Note model?
If the request body doesn’t have a title or a content, then spring will return a 400 BadRequest error to the client.
3. Get a Single Note (Get /api/notes/{noteId})
// Get a Single Note
@GetMapping("/notes/{id}")
public Note getNoteById(@PathVariable(value = "id") Long noteId) {
return noteRepository.findById(noteId)
.orElseThrow(() -> new ResourceNotFoundException("Note", "id", noteId));
}

The @PathVariable annotation, as the name suggests, is used to bind a path variable with a method parameter.
In the above method, we are throwing a ResourceNotFoundException whenever a Note with the given id is not found.
This will cause Spring Boot to return a 404 Not Found error to the client (Remember, we had added a @ResponseStatus(value = HttpStatus.NOT_FOUND) annotation to the ResourceNotFoundException class).
4. Update a Note (PUT /api/notes/{noteId})
// Update a Note
@PutMapping("/notes/{id}")
public Note updateNote(@PathVariable(value = "id") Long noteId,
@Valid @RequestBody Note noteDetails) {

Note note = noteRepository.findById(noteId)
.orElseThrow(() -> new ResourceNotFoundException("Note", "id", noteId));

note.setTitle(noteDetails.getTitle());
note.setContent(noteDetails.getContent());

Note updatedNote = noteRepository.save(note);
return updatedNote;
}

5. Delete a Note (DELETE /api/notes/{noteId})
// Delete a Note
@DeleteMapping("/notes/{id}")
public ResponseEntity<?> deleteNote(@PathVariable(value = "id") Long noteId) {
Note note = noteRepository.findById(noteId)
.orElseThrow(() -> new ResourceNotFoundException("Note", "id", noteId));

noteRepository.delete(note);

return ResponseEntity.ok().build();
  1. What is unknown error in line 1 of pom.xml?, tried to resolve by updating maven but did not work.

Hibernate Error executing DDL via JDBC Statement

72



in your CFG file please change the hibernate dialect

<!-- SQL dialect --><propertyname="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

fixed the problem





What is dialect class in Hibernate?

  • To connect to any database with hibernate, we need to specify the SQL dialect class in hibernate.cfg.xml

     Ex: To connect to oracle database we need to specify oracle dialect class in configuration xml as below.



  • Dialect class is java class, which contains code to map between java language data type database data type.
  • All Dialect classes extend the Dialect abstract class.
  • Dialect is used to convert HQL statements to data base specific statements
package com.cerotid.my_first_springhibernate_project;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {

Alien alien = new Alien();
alien.setAid(101);
alien.setColor("Green");
alien.setAname("Ram");

Configuration con = new Configuration().configure().addAnnotatedClass(Alien.class);

ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(con.getProperties()).build();

SessionFactory sf = con.buildSessionFactory(sr);

Session session = sf.openSession();

Transaction tx = session.beginTransaction();

session.save(alien);
tx.commit();
}
}

package com.cerotid.my_first_springhibernate_project;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "alien_table")
public class Alien {
@Id
private int aid;
private String aname;
@Column(name = "alien_color")
private String color;

public int getAid() {
return aid;
}

public void setAid(int aid) {
this.aid = aid;
}

public String getAname() {
return aname;
}

public void setAname(String string) {
this.aname = string;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

@Override
public String toString() {
return "Alien [aid=" + aid + ", aname=" + aname + ", color=" + color + "]";
}

}

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">My1p@hand</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>

use world;

show tables;

select * from alien_table;

To Fetch the data form MYSQL to Server side
package com.cerotid.my_first_springhibernate_project;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {

Alien alien = new Alien();
Configuration con = new Configuration().configure().addAnnotatedClass(Alien.class);

ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(con.getProperties()).build();

SessionFactory sf = con.buildSessionFactory(sr);

Session session = sf.openSession();

Transaction tx = session.beginTransaction();

alien = (Alien) session.get(Alien.class, 101);

tx.commit();

System.out.println(alien);
}
}
Use of Embeddable annotation:
package com.cerotid.my_first_springhibernate_project;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {

AlienName alienName = new AlienName();
alienName.setFirstName("Ram");
alienName.setMiddleName("Prasad");
alienName.setLastName("Neupane");
Alien alien = new Alien();
alien.setAid(101);
alien.setColor("Green");
alien.setAname(alienName);

Configuration con = new Configuration().configure().addAnnotatedClass(Alien.class).addAnnotatedClass(AlienName.class);

ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(con.getProperties()).build();

SessionFactory sf = con.buildSessionFactory(sr);

Session session = sf.openSession();

Transaction tx = session.beginTransaction();

session.save(alien);

tx.commit();

System.out.println(alien);
}
}

package com.cerotid.my_first_springhibernate_project;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "alien_table")
public class Alien {
@Id
private int aid;
private AlienName aname;
@Column(name = "alien_color")
private String color;
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public AlienName getAname() {
return aname;
}
public void setAname(AlienName aname) {
this.aname = aname;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Alien [aid=" + aid + ", aname=" + aname + ", color=" + color + "]";
}


}
package com.cerotid.my_first_springhibernate_project;

import javax.persistence.Embeddable;

@Embeddable
public class AlienName {

private String firstName;
private String lastName;
private String middleName;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getMiddleName() {
return middleName;
}

public void setMiddleName(String middleName) {
this.middleName = middleName;
}

@Override
public String toString() {
return "AlienName [firstName=" + firstName + ", lastName=" + lastName + ", middleName=" + middleName + "]";
}

}
Mapping Relations:
OneToOne
package com.cerotid.my_first_springhibernate_project;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {

Laptop laptop = new Laptop();
laptop.setLid(101);
laptop.setLname("Dell");

Student stud = new Student();
stud.setSname("Ram");
stud.setRollno(1);
stud.setSmark(50);
stud.setLaptop(laptop);

Configuration con = new Configuration().configure().addAnnotatedClass(Laptop.class)
.addAnnotatedClass(Student.class);

ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(con.getProperties()).build();

SessionFactory sf = con.buildSessionFactory(sr);

Session session = sf.openSession();

Transaction tx = session.beginTransaction();

session.save(stud);
session.save(laptop);

tx.commit();

}
}
package com.cerotid.my_first_springhibernate_project;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Laptop {

@Id
private int lid;
private String lname;

public int getLid() {
return lid;
}

public void setLid(int lid) {
this.lid = lid;
}

public String getLname() {
return lname;
}

public void setLname(String lname) {
this.lname = lname;
}

}
package com.cerotid.my_first_springhibernate_project;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity
public class Student {
@Id
private int rollno;
private String sname;
private int smark;
@OneToOne
private Laptop laptop;

public int getRollno() {
return rollno;
}

public void setRollno(int rollno) {
this.rollno = rollno;
}

public String getSname() {
return sname;
}

public void setSname(String sname) {
this.sname = sname;
}

public int getSmark() {
return smark;
}

public void setSmark(int smark) {
this.smark = smark;
}

public Laptop getLaptop() {
return laptop;
}

public void setLaptop(Laptop laptop) {
this.laptop = laptop;
}

@Override
public String toString() {
return "Student [rollno=" + rollno + ", sname=" + sname + ", smark=" + smark + "]";
}

}
ManyToMany

package com.cerotid.my_first_springhibernate_project;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {

Laptop laptop = new Laptop();
laptop.setLid(101);
laptop.setLname("Dell");

Student stud = new Student();
stud.setSname("Ram");
stud.setRollno(1);
stud.setSmark(50);
stud.getLaptop().add(laptop);
laptop.getStudent().add(stud);

Configuration con = new Configuration().configure().addAnnotatedClass(Laptop.class)
.addAnnotatedClass(Student.class);

ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(con.getProperties()).build();

SessionFactory sf = con.buildSessionFactory(sr);

Session session = sf.openSession();

Transaction tx = session.beginTransaction();

session.save(stud);
session.save(laptop);

tx.commit();

}
}
package com.cerotid.my_first_springhibernate_project;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;

@Entity
public class Laptop {

@Id
private int lid;
private String lname;
@ManyToMany
private List<Student> student = new ArrayList<Student>();

public int getLid() {
return lid;
}

public void setLid(int lid) {
this.lid = lid;
}

public String getLname() {
return lname;
}

public void setLname(String lname) {
this.lname = lname;
}

public List<Student> getStudent() {
return student;
}

public void setStudent(List<Student> student) {
this.student = student;
}

}
package com.cerotid.my_first_springhibernate_project;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Student {
@Id
private int rollno;
private String sname;
private int smark;
@OneToMany(mappedBy = "student")
private List<Laptop> laptop = new ArrayList<Laptop>();

public int getRollno() {
return rollno;
}

public void setRollno(int rollno) {
this.rollno = rollno;
}

public String getSname() {
return sname;
}

public void setSname(String sname) {
this.sname = sname;
}

public int getSmark() {
return smark;
}

public void setSmark(int smark) {
this.smark = smark;
}

public List<Laptop> getLaptop() {
return laptop;
}

public void setLaptop(List<Laptop> laptop) {
this.laptop = laptop;
}

@Override
public String toString() {
return "Student [rollno=" + rollno + ", sname=" + sname + ", smark=" + smark + "]";
}

}

No comments:

Post a Comment