Constructor Expression in TypedQuery with CriteriaQuery - jpql

I was using JPQL NamedQueries earlier in order to get some values from one db-table A and put it into PartsOfA via a constructor expression like this: SELECT new ...PartsOfA(a.member) from A a where ...
Now I am trying to do the same with a TypedQuery which shall be created by using a CriteriaQuery.
Is it possible? If yes, how?

Yes you can.
Example:
TransferObject:
public class BasicTeacherInfo {
private String firstName;
private String lastName;
public BasicTeacherInfo(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
Query
CriteriaQuery<BasicTeacherInfo> query = cb.createQuery(BasicTeacherInfo.class);
Root<Teacher> teacher = query.from(Teacher.class);
query.multiselect(teacher.get("firstName"),teacher.get("lastName"));
List<BasicTeacherInfo> results = em.createQuery(query).getResultList();
for (BasicTeacherInfo info : results) {
System.out.println("First name = " + info.getFirstName() + " "
+ "Last Name = " + info.getLastName());
}
examples from http://www.thejavageek.com/2014/04/27/multiselect-criteria-api/
By the way: You seem to misuse TypedQuery word. A Criteria Query is not a TypedQuery. TypedQuery<T> is the Type of e.g. a named query.

Related

Call print of Switch case - from a blueprint class to a main class

I am having class about java, and There is a assignment that I must do, but I am stuck. lol
This is what she asked:
Write a java blueprint class that models an Airline Reservation and adheres to the following
criteria:
o5 instance variables: first name, last name, flight number, seat number , ticket number
oA default constructor
oA constructor that takes five arguments
oA setter and getter for each field that simply sets and gets the field value.
oA method called “retrieveSeatingClass” which returns a “seating class” for each seat number (use
a switch statement)
▪seats 1-2: First Class
▪seats 3-4: Second Class
▪seats 5-6 Third Class
▪seats 7-8: Fourth Class
I did it. But now in the main class, she wants me to call the result. And I am struggling to do it. Here follows my code.
Entered code here:
public class AirlineReservation {
String firstName;
String lastName;
String flightNumber;
int seatNumber;
int ticketNumber;
public AirlineReservation() {
}
public AirlineReservation(String firstName, String lastName, String flightNumber, int seatNumber,
int ticketNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.flightNumber = flightNumber;
this.seatNumber = seatNumber;
this.ticketNumber = ticketNumber;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public void setSeatNumber(int seatNumber) {
this.seatNumber = seatNumber;
}
public void setTicketNumber(int ticketNumber) {
this.ticketNumber = ticketNumber;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getFlightNumber() {
return flightNumber;
}
public int getSeatNumber() {
return seatNumber;
}
public int getTicketNumber() {
return ticketNumber;
}
public String retrieveSeatingClass() {
int classNumber = seatNumber;
switch (classNumber) {
case 1:
case 2:
System.out.println("First Class");
break;
case 3:
case 4:
System.out.println("Second Class");
break;
case 5:
case 6:
System.out.println("Third Class");
break;
case 7:
case 8:
System.out.println("Fourth Class");
break;
}
return "seat";
}
import java.util.Scanner;
public class AirlineReservationTestHarness {
public static void main (String[ ]args) {
AirlineReservation passager1 = new AirlineReservation("Raquel","Cristina", "400", 1, 456789);
System.out.println("Passager: " + passager1.getFirstName());
System.out.println("Last name: " + passager1.getLastName());
System.out.println("Flight Number" + passager1.getFlightNumber());
System.out.println("Seat: " + passager1.getSeatNumber());
System.out.println("Your ticket number is: " + passager1.getTicketNumber());
`enter code here` System.out.println("Your data is: " + passager1.getFirstName() + assager1.getLastName() + passager1.getFlightNumber() + passager1.getSeatNumber() + passager1.getTicketNumber() + " and your in a " + );
}
}
In my main, how do I call it for when the seat it 1 it appears First Class?

C#: how to display the employee names with lowest salary

I have to create an appropriate GUI to enter information for at least 10 employee. for each employee i have to enter the following information. employee ID, employee first name, employee last name and yearly salary. besides i have to check for the correctness of the input data. in addition i need to create a separate class EMPLOYEE, containing employee information: employee ID, first name , last name and yearly salary. the class should have constructors properties and methods. all the employee information has to be stored in a array of type employee. after reading form GUI the information about particular employee , also create an object of class employee(element of the array) with the relevant constructor. the user would like to be able to find the employee with lowest yearly salary despite of having more than one employee with lowest yearly salary. and display information about them. user should be provided with appropriate GUI to display the required information.
i need to assure including in my program appropriate code for handling exceptions and also methods where appropriate.
here is the class employee:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_employee
{
class Employee
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public Employee()
{
employeeID = 0;
fullName = "";
lastName = "";
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = 0.0;
}
public Employee(int empIDValue, string fullNameVal, string lastNameVal, double salaryValue)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = salaryValue;
}
public int EmployeeIDNum
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string FullName
{
get
{
return fullName;
}
set
{
fullName = value;
}
}
public int Getinfo
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string employeeInformationToString()
{
// employeeID = Convert.ToInt32(this.textBox1.Text);
return (Convert.ToString(employeeID) + " " + fullName + " " + lastName + " " + Convert.ToString(salary));
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project_employee
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void Searchbtn_Click(object sender, EventArgs e)
{
employee[0] = new Employee();
employee[1] = new Employee(17433, "Adrian", "Smith", 8000.00);
employee[2] = new Employee(17434, "Stephen", "Rad", 9000.00);
employee[3] = new Employee(17435, "Jesse", "Harris", 800.00);
employee[4] = new Employee(17436, "jonatan", "Morris", 9500.00);
employee[5] = new Employee(17437, "Morgen", "Freeman", 12000.00);
employee[6] = new Employee(17438, "Leory", "Gomez", 10200.00);
employee[7] = new Employee(17439, "Michael", "Brown", 9000.00);
employee[8] = new Employee(17440, "Andrew", "White", 3500.00);
employee[9] = new Employee(17441, "Maria", "Carson", 12000.00);
//employee[10] = new Employee(17442, "Mark", "Jonson", 17000.00);
for(int i = 0; i < 10; i++)
{
string employeeString = employee[i].employeeInformationToString() + "\r\n";
richTextBox1.AppendText(employeeString);
}
}
Employee[] employee = new Employee[10];
private void getinfibtn_Click(object sender, EventArgs e)
{
Find();
}
private void Find()
{
}
}
}
My question is:
How the user can find the employee with the lowest yearly salary. i have to make sure that there can be more than one employee with lowest yearly salary and display the information about them. providing the user with an appropriate GUI (e.g a message box) to display the required information with including appropriate code for handling exceptions and also use methods where appropriate?
You need to make your class Employee to implement the IComparable interface, then compare the objects against the salary and in the other class sort the array...
Example:
public class Employee :IComparable<Employee>
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public int CompareTo(Employee other)
{
return salary.CompareTo(other.salary);
}
}
private void Find()
{
Array.Sort(employee); // after this Employee is sorted
employee[0];
or
employee[9];
}
this will give a list of lowest salary emplyees
employee.Add(new Employee(17434, "Stephen", "Rad", 9000.00));
employee.Add(new Employee(17435, "Jesse", "Harris", 800.00));
employee.Add(new Employee(17436, "jonatan", "Morris", 9500.00));
var c = employee.OrderBy(i => i.salary).ToList();
var e = employee.Where(i => Math.Abs(i.salary - c[0].salary) < 1).ToList();
Modified you code a little bit
class Employee
{
private int employeeID;
private string fullName;
private string lastName;
private double salary;
public double Salary
{
get
{
return salary;
}
set
{
salary = value;
}
}
//public Employee()
//{
// employeeID = 0;
// fullName = "";
// lastName = "";
// salary = 0.0;
//}
//public Employee(int empIDValue, string fullNameVal, string lastNameVal)
//{
// employeeID = empIDValue;
// fullName = fullNameVal;
// lastName = lastNameVal;
// salary = 0.0;
//}
public Employee(int empIDValue, string fullNameVal, string lastNameVal, double salaryValue)
{
employeeID = empIDValue;
fullName = fullNameVal;
lastName = lastNameVal;
salary = salaryValue;
}
public int EmployeeIDNum
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string FullName
{
get
{
return fullName;
}
set
{
fullName = value;
}
}
public int Getinfo
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string employeeInformationToString()
{
// employeeID = Convert.ToInt32(this.textBox1.Text);
return (Convert.ToString(employeeID) + " " + fullName + " " + lastName + " " + Convert.ToString(salary));
}
}
and to get min values in list
var minEmpSalarylist = employee.Where(x => x.Salary == employee.Min(y => y.Salary)).ToList();
If default constructor is present then all minEmpSalarylist become initialized with default constructor.
and
employee[0] = new Employee();
to change it to
employee[0] = new Employee(17433, "XXX", "YYY", 8000.00);

Spring-data-cassandra's CassandraTemplate returns String, not a specified Object, when run queryForObject function.

I've been going through the Spring Data Cassandra documentation (http://docs.spring.io/spring-data/cassandra/docs/1.0.1.RELEASE/reference/html/cassandra.core.html)
Basically, with proper annotation, I hoped the CassandraTemplate maps a row to a POJO object, but it didn't work as I expected.
For the call,
cassandraOps.queryForObject(s, Person.class)
I received an error as following:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to Person
Anything that I'm missing? Following is the same copy and paste from the doc above.
Person Class looks like:
#Table
public class Person {
#PrimaryKey
private String id;
private String name;
private int age;
public Person(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
#Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
and the application class looks like...:
public class CassandraApp {
private static final Logger LOG = LoggerFactory.getLogger(CassandraApp.class);
private static Cluster cluster;
private static Session session;
public static void main(String[] args) {
try {
cluster = Cluster.builder().addContactPoints(InetAddress.getLocalHost()).build();
session = cluster.connect("mykeyspace");
CassandraOperations cassandraOps = new CassandraTemplate(session);
cassandraOps.insert(new Person("1234567890", "David", 40));
Select s = QueryBuilder.select().from("person");
s.where(QueryBuilder.eq("id", "1234567890"));
LOG.info(cassandraOps.queryForObject(s, Person.class).getId());
cassandraOps.truncate("person");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
CassandraTemplate's queryForObject(String,Class) is not meant for arbitrary object mapping. It is modeled after JdbcTemplate's queryForObject(String,Class) method. It's intended to take types that the Cassandra driver can convert directly.
To convert arbitrary application-defined classes, use queryForObject(String,RowMapper<T>) or one of its overloads. CqlTemplate doesn't know how to map arbitrary classes; you have to supply the RowMapper<T> implementation for your class T.
you can do it like this way:-
String myQuery = "select * from person where id=1234567890";
Person personObj = cassandraOperations.selectOne(myQuery, Person.class);
<<
For all
List<Person> personListObj = cassandraOperations.select(myQuery, Person.class); >>
this work for me using cassandraTemplete object perfectly... didn't try for cassandraOperation.
also you might need #Column(value = "your_columnName_in_DB") if your pojo class's variable name is different
like
#Column(value = "name")
private String userName;
#Column(value = "age")
private int userAge;
revert here if its work?
Also can you help me pass dynamic value to that myQuery string.. using object[] same like prepareStatment in SQL
thanks.

Sort JPA relational entity lists

I'm using PrimeFaces to display information in a DataTable. The data in the datatable is actually a List of entity objects which is generated by OpenJPA. And the entities have relations to other entities. This means that there are Lists inside Lists.
For example, an entity called Authors, which has many Books. The data List<Authors> is listed in the datatable. And in order to sort the List i use Collections.sort() which of course doesn't work when i try to sort on the Authors book title. Because the title field is an instance of the Book class.
How do i go about to sort the Lists when there are relationships like this?
Thanks in advance.
Here is an example of sorting by books title, you need to sort your books list :
public static void main(String args[]) {
List<Author> list = new ArrayList<Author>();
for (int i=0;i<5;i++){
Author a = new Author();
a.setName("author"+i);
List<Book> books = new ArrayList<Book>();
for(int j=0;j<4;j++){
Random r = new Random();
char c = (char) (r.nextInt(26) + 'a');
Book b = new Book();
b.setTitle(c+"title");
books.add(b);
}
a.setBooks(books);
list.add(a);
}
/*
* At this point of time you have Authors list which you want to sort by book title.
* So you can do something like below if you want to do it through Collections.sort
*/
for(Author a : list){
Collections.sort(a.getBooks(), new Comparator<Book>(){
#Override
public int compare(Book o1, Book o2) {
return o1.getTitle().compareToIgnoreCase(o2.getTitle());
}});
}
System.out.println(list);
}
Author and Book used in above example:
import java.util.List;
public class Author {
private List<Book> books;
private String name;
#Override
public String toString() {
return "Author [books=" + books + ", name=" + name + "]";
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Book.java:
public class Book {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return "Book [title=" + title + "]";
}
}

Having trouble writing a constructor for a object inside another class

Please don't get mad, I am amiting this is help on my homework but I like to learn this and can't find it anywhere. I have looked for it and couldn't find anything like it, idk if I am looking in all the wrong places or for the wrong thing I have two other classes inside my code and having trouble creating another class with class objectives inside of it, I will show what I attempted and see if yall can please help me out. Also, I want to make sure I am using the keyword " this" right in my other two classes. She wanted us to use this in our program and the comments are what we are told to do:
public class Person
{
private String lastName;
private String firstName;
//default constructor
public Person()
{
lastName= null;
firstName = null;
}
//two-parameter constructor
public Person(String lastName, String firstName)
{
this.lastName=lastName;
this.firstName=firstName;
}
//copy constructor
public Person(Person object2)
{
this.lastName=object2.lastName;
this.firstName=object2.firstName;
}
// standard accessor method for each of the two fields
public String getLastName(String lastName)
{
lastName = this.lastName;
return lastName;
}
public String getFirstName(String firstName)
{
firstName = this.firstName;
return firstName;
}
public void setLastName(String lastName)
{
this.lastName=lastName;
}
public void setFirstName(String firstName)
{
this.firstName=firstName;
}
//mutator method for both fields—using standard mutator methods
public void setName(String lastName,String firstName)
{
this.lastName= lastName;
this.firstName = firstName;
}
//toString method
public String toString()
{
String str = “Last Name: “ + lastName + “\nFirst Name: “ + firstName;
return str;
}
//equals method
public boolean equals(Person name2)
{
boolean status;
if (this.lastName.equals(name2.lastName) && this.firstName.equals(name2.firstName))
status = true;
else
status = false;
return status;
}
//copy method
public Person copy()
{
Person copyObject = new Person(lastName, firstName);
return copyObject;
}
}
public class Date
{
private int month;
private int day;
private int year;
//default constructor
public Date()
{
this (0,0,0);
}
//three-parameter constructor
public Date(int month, int day, int year)
{
this.month = month;
this.day = day;
this.year = year;
}
//copy constructor
public Date(Date object2)
{
this (object2.month, object2.day, object2.year);
}
//standard accessor method for each field
public int getMonth(int month)
{
month = this.month;
return month;
}
public int getDay(int day)
{
day = this.day;
return day;
}
public int getYear(int year)
{
year = this.year;
return year;
}
//standard mutator method for each field
public void setMonth(int month)
{
this.month = month;
}
public void setDay(int day)
{
this.day = day;
}
public void setYear(int year)
{
this.year = year;
}
//mutator method for both fields—using standard mutator methods
public void setDate(int month, int day, int year)
{
this.month = month;
this.day = day;
this.year= year;
}
//toString method
public String toString()
{
String str = "Date:" + month+ " " + day + ", " + year;
return str;
}
//equals method
public boolean equals (Date object2)
{
boolean status;
if (this.month == object2.month && this.day == object2.day && this.year == object2.year)
status = true;
else
status = false;
return status;
}
//copy method
public Date copy()
{
Date copyObject = new Date(month, day, year);
return copyObject;
}
}
And this is what I have been trying for my other class and It shows an ERROR:
public class PersonalInfo
{
private Person name;
private Date birthday;
private int idNumber;
// the default constructor
public PersonalInfo()
{
Person name = new Person();
Date birthday = new Date();
this.idNumber = 0;
}
// A constructor that passes 6 parameters
public PersonalInfo(String lastName, String firstName, int month, int day, int year, int idNumber )
{
Person name = new Person(lastName, firstName);
Date birthday= new Date(month, day, year);
this.idNumber = idNumber;
}
}
Please help! And thank you for looking
Since you haven't specified the language or the error message, this is only a qualified guess. If this isn't the actual problem, provide more details.
public PersonalInfo()
{
Person name = new Person();
Date birthday = new Date();
this.idNumber = 0;
}
You are declaring new local variables name and birthday here, rather than using the class members. That means the class members never get initialized, and I suspect that's what the error is trying to tell you.
The right way to do this is to just refer directly to the variables:
this.name = new Person();
this.birthday = new Date();
or, since this is implied when there is no local variable or parameter with the same name:
name = new Person();
birthday = new Date();

Resources