Skip to content

Commit

Permalink
fix: import in PetDAO and remove unnecessary variable
Browse files Browse the repository at this point in the history
  • Loading branch information
jdegand committed Dec 21, 2024
1 parent f6343c8 commit 55a84ad
Showing 1 changed file with 20 additions and 20 deletions.
40 changes: 20 additions & 20 deletions Hibernate/PetDAO.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,23 @@

import java.util.*;
import java.util.logging.*;
import javax.persistence.*;
import jakarta.persistence.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.query.Query;

public class PetDAO {

public List<Pet> findNamedPetsBySpecies(Session session, String species) {
List<Pet> pets = session.createNativeQuery(
"SELECT * " +
"FROM Pet " +
"WHERE species like :species AND name is NOT NULL ")
.addEntity( Pet.class )
.setParameter("species", species)
.list();
return pets;
return session.createNativeQuery(
"SELECT * " +
"FROM Pet " +
"WHERE species like :species AND name is NOT NULL")
.addEntity(Pet.class)
.setParameter("species", species)
.list();
}

@Entity(name = "Pet")
@Table
public static class Pet {
Expand All @@ -32,16 +31,17 @@ public static class Pet {
public String name;
@Column
public String species;

public Pet() {}


public Pet() {
}

public Pet(Integer id, String name, String species) {
this.id = id;
this.name = name;
this.species = species;
}
}

public static void main(String[] args) {
LogManager logManager = LogManager.getLogManager();
Logger logger = logManager.getLogger("");
Expand All @@ -53,23 +53,23 @@ public static void main(String[] args) {
prop.setProperty("hibernate.hbm2ddl.auto", "create");

SessionFactory sessionFactory = new Configuration().addProperties(prop)
.addAnnotatedClass(Pet.class).buildSessionFactory();
.addAnnotatedClass(Pet.class).buildSessionFactory();

Session session = sessionFactory.openSession();
session.beginTransaction();

Pet dog = new Pet(0, "Lady", "Dog");
Pet cat = new Pet(1, "Max", "Cat");
Pet camel = new Pet(2, null, "Camel");

session.save(dog);
session.save(cat);
session.save(camel);
session.flush();

PetDAO petDao = new PetDAO();
List<Pet> pets = petDao.findNamedPetsBySpecies(session, "Cat");
for(Pet p : pets) {
for (Pet p : pets) {
System.out.println(p.id);
System.out.println(p.name);
System.out.println(p.species);
Expand Down

0 comments on commit 55a84ad

Please sign in to comment.