Skip to content

Instantly share code, notes, and snippets.

@mhewedy
Created November 11, 2016 00:08
Show Gist options
  • Save mhewedy/296ef7471f22c0c3284a06d8ed40cb59 to your computer and use it in GitHub Desktop.
Save mhewedy/296ef7471f22c0c3284a06d8ed40cb59 to your computer and use it in GitHub Desktop.
using List<Map<String, Object>> as return type for hql queries
package test;
import java.util.List;
import java.util.Map;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@EnableJpaRepositories
@SpringBootApplication
public class HibernateSelectMapApplication implements CommandLineRunner {
private StudentRepo studentRepo;
public HibernateSelectMapApplication(StudentRepo studentRepo) {
this.studentRepo = studentRepo;
}
public static void main(String[] args) {
SpringApplication.run(HibernateSelectMapApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
Student s1 = new Student(null, "Boody", "Abdullah", 2, "Egypt");
Student s2 = new Student(null, "Farida", "Abdullah", 2, "Egypt");
studentRepo.save(s1);
studentRepo.save(s2);
Iterable<Student> findAll = studentRepo.findAll();
System.out.println(findAll);
List<Map<String, Object>> map = studentRepo.findFirstLastNamesAndGrade();
System.out.println(map);
}
}
@Repository
interface StudentRepo extends CrudRepository<Student, Long> {
@Query("select new map (o.firstName as firstName, o.lastName as lastName, o.grade as grade) from Student o")
List<Map<String, Object>> findFirstLastNamesAndGrade();
}
@Data
@Table
@Entity
@NoArgsConstructor
@AllArgsConstructor
class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String firstName;
String lastName;
Integer grade;
String country;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment