I have a table with 5 columns (id |state_abbrevation | state_name | area_code | cities ). I have to store all the values as key value pair where key= state_abbrevation and Value = (area_code) cities.
Also state_abbrevation has duplicates. A sample data is shown below:
id | state_abbrevation | state_name | area_code | cities
----+-------------------+--------------+-----------+---------------------
1 | AK | Alaska | 907 | Juneau
2 | AL | Alabama | 205 | Birmingham
3 | AL | Alabama | 251 | Mobile
4 | AL | Alabama | 256 | Huntsville
5 | AL | Alabama | 334 | Montgomery
6 | AL | Alabama | 938 | Florence/Huntsville
7 | AR | Arkansas | 479 | Ft. Smith
8 | AR | Arkansas | 501 | Little Rock
9 | AR | Arkansas | 870 | Jonesboro
10 | AZ | Arizona | 480 | Scottsdale
11 | AZ | Arizona | 520 | Tucson
12 | AZ | Arizona | 602 | Phoenix
13 | AZ | Arizona | 623 | Glendale
14 | AZ | Arizona | 928 | Flagstaff
15 | CA | California | 209 | Modesto
16 | CA | California | 213 | Los Angeles
17 | CA | California | 310 | West Hollywood
18 | CA | California | 323 | Hollywood
What's the best solution to store in key value pair where key = AL & Value = Area code and City for all state_abbrevation= AL.
Example for Hashmap I want:
KEY, VALUE
AK, (907) Juneau
AL, (205) Birmingham
(251) Mobile
(256) Huntsville
(938) Florence
.......and so on.
Here's my working code using Hibernate:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
public class HibernateCriteriaExamples {
public static void main(String[] args) {
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Criteria criteria = session.createCriteria(State.class);
//List<State> stateList = criteria.list();
List<String> stateAbbrevationList = criteria.setProjection(Projections.distinct(Projections.property("stateAbbrevation"))).list();
HashMap<String,List> cityAreacodeAndState = new HashMap<String,List>();
for(int i=0; i<stateAbbrevationList.size();i++)
{
String abbrevation = stateAbbrevationList.get(i);
//System.out.println(abbrevation);
Criteria criteriaareaCodeWithCity = session.createCriteria(State.class);
List<State> stateObject = criteriaareaCodeWithCity.add(Restrictions.eq("stateAbbrevation", abbrevation)).list();
List<String> formattedAreaCodeAndCity =new ArrayList<String>();
for(int j=0; j<stateObject.size();j++)
{
State state = (State)stateObject.get(j);
int a = state.getAreacode();
String b = state.getCities();
String c = "("+a+") "+b;
// System.out.println(c);
formattedAreaCodeAndCity.add(c);
}
cityAreacodeAndState.put(abbrevation, formattedAreaCodeAndCity);
}
System.out.println("---------------PRINTING REQUIRED DATA------------------");
for (HashMap.Entry<String,List> formattedAreaCodeAndCity1 : cityAreacodeAndState.entrySet())
{
System.out.println(formattedAreaCodeAndCity1.getKey() + "," + formattedAreaCodeAndCity1.getValue());
}
tx.commit();
sessionFactory.close();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You can use HashMap as well as List.
Your HashMap key will be state_abbrevation and your value (i.e., List) will contain area_code and cities.
HashMap<String, List<String>> data = new HashMap<>();
..
while(rs.next()) {
List<String> temp = new ArrayList<>();
temp.add(rs.getString("area_code"));
temp.add(rs.getString("cities"));
data.put(rs.getString("state_abbrevation"), temp);
}
to get the data related to state CA
data.get("CA").get(0) // -> gives area_code related to state "CA"
data.get("CA").get(1) // -> gives cities related to state "CA"
As was mentioned in comments, you can use value object to keep data for state:
public Map<String, State> getStatesMap() {
... execute query and get resultSet
Map<String, State> result = new HashMap<>();
while (resultSet.next()) {
result.put(
resultSet.getString("state_abbrevation"),
new State(
resultSet.getString("area_code"),
resultSet.getString("cities")
)
);
}
return result;
}
private class State {
private final String area;
private final String cities;
public State(String area, String cities) {
this.area = area;
this.cities = cities;
}
public String getArea() {
return area;
}
public String getCities() {
return cities;
}
}
Related
I have customer entity that have List of accounts and each entity have audited tables,so tables generated will be :
(CUSTOMERS
,ACCOUNTS
,CUSTOMERS_AUD
,ACCOUNTS_AUD)
how can I connect the change of accounts with the change of customer in one rev number? hibernate envers gives separated version (rev number) for each table ?
The generated tables of my code:
CUSTOMERS_AUD TABLE
| ID | REV | REVTYPE |name |account_num|ACCOUNTID|
|:----|------:|:-------:|:----:|:---------:|:-------:|
| 1 | 1 | 0 |Ann |1234567897 |1 |
| 1 | 3 | 1 |Alex |1234567897 |1 |
| 1 | 5 | 1 |Alex |7777777777 |1 |
ACCOUNTS_AUD TABLE
| ID | REV | REVTYPE |name |account_num|
|:-----------|------:|:-------:|:----:|:---------:|
| 1 | 2 | 0 |Ann |1234567897 |
| 1 | 4 | 1 |Alex |7777777777 |
SAMPLE ENTITIES
#Entity
#Table(name="CUSTOMERS")
#Audited
public class Customer implements Serializable {
.
.
#ManyToOne
#org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.REPLICATE)
#JoinColumn(name="ACCOUNTNUMBERCOMBOBOXID", nullable=true)
private Account accountNumberComboBox;
public static final String REF_CUSTOMERS_ACCOUNTS = "refCustomersAccounts";
#OneToMany(mappedBy = "refCustomers")
#org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.REPLICATE)
private List<Account> refCustomersAccounts;
.
.
.
}
#Entity
#Table(name="ACCOUNTS")
#Audited
public class Account implements Serializable {
.
.
public static final String REF_CUSTOMERS = "refCustomers";
#ManyToOne
#org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.REPLICATE)
#JoinColumn(name="REFCUSTOMERSID", nullable=true)
private Customer refCustomers;
.
.
.
}
THE RESULTS THAT I WANT
CUSTOMERS_AUD TABLE
| ID | REV | REVTYPE |name |account_num|ACCOUNTID|
|:----|------:|:-------:|:----:|:---------:|:-------:|
| 1 | 1 | 0 |Ann |1234567897 |1 |
| 1 | 2 | 1 |Alex |1234567897 |1 |
| 1 | 3 | 1 |Alex |7777777777 |1 |
ACCOUNTS_AUD TABLE
| ID | REV | REVTYPE |name |account_num|
|:-----------|------:|:-------:|:----:|:---------:|
| 1 | 1 | 0 |Ann |1234567897 |
| 1 | 2 | 0 |Ann |1234567897 |
| 1 | 3 | 1 |Alex |7777777777 |
Spring boot application
#SpringBootApplication
public class JpaDemoApplication implements CommandLineRunner {
#Autowired
private ApplicationContext context;
public static void main(String[] args) {
SpringApplication.run(JpaDemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
CustomerRepo customerRepo = context.getBean(CustomerRepo.class);
AccountRepo accountRepo = context.getBean(AccountRepo.class);
AccountTypeRepo accountTypeRepo = context.getBean(AccountTypeRepo.class);
Accounts account = new Accounts();
Customers customer = new Customers();
customer.setId(1L);
account.setId(1L);
account.setFromDate(new Date());
account.setToDate(new Date());
account.setNewAcountNumber("1234567897");
account.setOwner("Ann");
customer.setAccountNumber(account.getNewAcountNumber());
customer.setCode("CODE");
customer.setName(account.getOwner());
customer.setFromDate(new Date());
customer.setToDate(new Date());
customer.setAccountNumberComboBox(account);
accountRepo.save(account);
customerRepo.save(customer);//0
customer.setName("Alex");
customerRepo.save(customer);//1
account.setNewAcountNumber("7777777777");
accountRepo.save(account);
}
}
Account Repo
#Repository
public interface AccountRepo extends CrudRepository<Accounts,Long> {
}
Customer Repo
#Repository
public interface CustomerRepo extends CrudRepository<Customers, Long> {
}
The revision number is associated with the transaction, so whatever operations you perform in a single transaction will be audited and stored with the same revision number, always.
Since you did not show your persistence code I can only guess at this point that the code is likely saving the Customer entity in one transaction and in a subsequent transaction you're saving the Account entity.
If you save them both within the same transaction, they'll get the same revision number assigned to their audit rows.
I have a product class where there is an #OneToMany association for a list of buyers. What I want to do is that buyer search performed by the association when I search for a product, use a null constraint for the end date column of the Buyer table. How to do this in a list mapping like this, below.
// it would be something I needed cri.createCriteria("listaBuyer", "buyer).add(Restriction.isNull("finalDate"));
Example
Registered data
product code | initial date | final date |
-------------------------------------------------------
1 | 2016-28-07 | 2017-28-07 |
------------------------------------------------------
2 | 2016-10-08 | 2017-28-07 |
------------------------------------------------------
3 | 2017-28-08 | |
-----------------------------------------------------
4 | 2017-30-08 | |
Product Class
public class Product {
#OneToMany(targetEntity=Buyer.class, orphanRemoval=true, cascade={CascadeType.PERSIST,CascadeType.MERGE}, mappedBy="product")
#LazyCollection(LazyCollectionOption.FALSE)
public List<Buyer> getListaBuyer() {
if (listaBuyer == null) {
listaBuyer = new ArrayList<Buyer>();
}
return listaBuyer;
}
built criterion
Criteria cri = getSession().createCriteria(Product.class);
cri.createCriteria("status", "sta");
cri.add(Restrictions.eq("id", Product.getId()));
return cri.list();
Expected outcome
product code | initial date | final date |
-------------------------------------------------------
3 | 2017-28-08 | |
-----------------------------------------------------
4 | 2017-30-08 | |
Returned result
product code | initial date | final date |
-------------------------------------------------------
1 | 2016-28-07 | 2017-28-07 |
------------------------------------------------------
2 | 2016-10-08 | 2017-28-07 |
------------------------------------------------------
3 | 2017-28-08 | |
-----------------------------------------------------
4 | 2017-30-08 | |
I have a question:
I have such a BDD table:
And the following set of "Dishes"
| Dish name |calories| quality | cost |
| grilled chicken| 400 | high | 12 |
| lasagna | 800 | low | 7 |
| gnocchi | 700 | high | 12 |
| pizza | 400 | low | 7 |
| snitzel | 400 | high | 12 |
And the following set of "Beverages"
| Beverage name | volume | quality | cost |
| coke | 35 | high | 5 |
| fanta | 35 | low | 2 |
| wine | 50 | high | 5 |
| beer | 50 | low | 2 |
| sprite | 35 | high | 5 |
and this is the implementation method os BDD data table.
public void the_following_set_of(String type, DataTable list) throws Throwable
{
if (type.equals("Dishes"))
{
List<List<String>> dishes = list.raw();
String[][] newdishes = new String[6][4];
newdishes.equals(dishes.toArray(newdishes));
for (int i = 1; i < 6; i++)
{
if (newdishes[i][2] == "high")
kalite.equals(Quality.high);
else
kalite.equals(Quality.low);
dishess.add(new Dish(newdishes[i][0], Integer.parseInt(newdishes[i][1]), kalite, Integer.parseInt(newdishes[i][3])));
}
}
if (type.equals("Beverages"))
{
List<List<String>> beverages = list.raw();
String[][] newbeverages = new String[6][4];
newbeverages = beverages.toArray(newbeverages);
for (int i = 1; i < 6; i++)
{
if (newbeverages[i][2] == "high")
kalite.equals(Quality.high);
else
kalite.equals(Quality.low);
beveragess.add(new Beverage(newbeverages[i][0], Integer.parseInt(newbeverages[i][1]), kalite, Integer.parseInt(newbeverages[i][3])));
}
}
restaurant.createMenu(dishess, beveragess);
}
I couldn't survive from ArrayStoreException here. Normally i'm trying to do cucumber feature testing, but when i run it, i encounter this problem.
When I run it eclipse says the problem is on this line:
newdishes.equals(dishes.toArray(newdishes));
How can i solve it?
Thanks.
Hi I have a table parent and its fields are
mysql> select * from parent;
+----+----------+------------+-----------------------------------+---------+------+
| id | category | is_deleted | name | version | cid |
+----+----------+------------+-----------------------------------+---------+------+
| 1 | default | | Front Office | 0 | NULL |
| 2 | default | | Food And Beverage | 0 | NULL |
| 3 | default | | House Keeping | 0 | NULL |
| 4 | default | | General | 0 | NULL |
| 5 | client | | SPA | 0 | NULL |
| 7 | client | | house | 0 | NULL |
| 8 | client | | test | 0 | NULL |
| 9 | client | | ggg | 0 | 1 |
| 10 | client | | dddd | 0 | 1 |
| 11 | client | | test1 | 0 | 1 |
| 12 | client | | java | 0 | 1 |
| 13 | client | | dcfdcddd | 0 | 1 |
| 14 | client | | qqqq | 0 | 1 |
| 15 | client | | nnnnnn | 0 | 1 |
| 16 | client | | category | 0 | 1 |
| 17 | client | | sukant | 0 | 1 |
| 18 | client | | bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb | 0 | 1 |
I have another table parent_question
mysql> select * from parent_question;
+----+------------+---------+-----+------+
| id | is_deleted | version | pid | qid |
+----+------------+---------+-----+------+
| 1 | | 0 | 1 | 1 |
| 2 | | 0 | 1 | 2 |
| 3 | | 0 | 1 | 3 |
| 4 | | 0 | 1 | 4 |
| 5 | | 0 | 1 | 5 |
| 6 | | 0 | 1 | 6 |
| 7 | | 0 | 2 | 7 |
| 8 | | 0 | 2 | 1 |
| 9 | | 0 | 2 | 2 |
| 10 | | 0 | 2 | 8 |
| 11 | | 0 | 3 | 9 |
| 12 | | 0 | 3 | 1 |
| 13 | | 0 | 3 | 10 |
| 14 | | 0 | 3 | 11 |
| 15 | | 0 | 4 | 12 |
| 16 | | 0 | 1 | 1 |
| 17 | | 0 | 1 | 2 |
| 18 | | 0 | 1 | 3 |
| 19 | | 0 | 5 | 13 |
| 20 | | 0 | 2 | 7 |
| 21 | | 0 | 2 | 2 |
| 22 | | 0 | 1 | 14 |
| 23 | | 0 | 1 | 15 |
| 24 | | 0 | 1 | 16 |
| 25 | | 1 | 1 | 17 |
| 26 | | 0 | 1 | 21 |
| 27 | | 0 | 2 | 22 |
| 28 | | 0 | 13 | 23 |
| 29 | | 0 | 9 | 24 |
| 30 | | 0 | 12 | 25 |
| 31 | | 0 | 12 | 26 |
| 32 | | 0 | 12 | 27 |
| 33 | | 0 | 12 | 28 |
| 34 | | 0 | 14 | 29 |
| 35 | | 0 | 15 | 30 |
| 36 | | 0 | 10 | 31 |
| 37 | | 0 | 4 | 32 |
| 38 | | 0 | 16 | 33 |
| 39 | | 0 | 10 | 34 |
| 40 | | 0 | 3 | 35 |
| 41 | | 0 | 17 | 36 |
| 42 | | 0 | 1 | 37 |
| 43 | | 0 | 1 | 38 |
| 44 | | 0 | 18 | 39 |
| 45 | | 0 | 18 | 40 |
+----+------------+---------+-----+------+
45 rows in set (0.00 sec)
and this is my question table
ysql> select * from question;
----+----------+------------+------------------------------------------------------------+--
id | category | is_deleted | question | v
----+----------+------------+------------------------------------------------------------+--
1 | default | | Staff Courtesy |
2 | default | | Staff Response |
3 | default | | Check In |
4 | default | | Check Out |
5 | default | | Travel Desk |
6 | default | | Door Man |
7 | default | | Restaurant Ambiance |
8 | default | | Quality Of Food |
9 | default | | Cleanliness Of The Room |
10 | default | | Room Size |
11 | default | | Room Amenities |
12 | default | | Any Other Comments ? |
13 | client | | How is Food? |
14 | client | | test question |
15 | client | | test1 |
16 | client | | test2 |
17 | client | | test2 |
18 | client | | test2 |
19 | client | | working |
20 | client | | sss |
21 | client | | ggggg |
22 | client | | this is new question |
23 | client | | dddddddddddd |
24 | client | | ggggggggggggggggg |
25 | client | | what is a class? |
26 | client | | what is inheritance |
27 | client | | what is an object |
28 | client | | what is an abstract class? |
29 | client | | qqqq |
30 | client | | nnnn question |
31 | client | | add some |
32 | client | | general question |
33 | client | | category question |
34 | client | | hhhhhhhh |
35 | client | | this is hos |
36 | client | | gggg |
37 | client | | dddd |
38 | client | | ddddd |
39 | client | | bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb |
40 | client | | ggg |
----+----------+------------+------------------------------------------------------------+--
what I know I have pid of parent_question table;
What I want question of question table;
for example.If I were given to find the question whose pid is 18.
So from the parent_question table I can know qid is 39 and 40 and from the question table 39 refers to bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb and 40 refers to ggg
What i tried
String queryString="SELECT distinct q FROM Question q , ParentQuestion pq ,Parent p where pq.qid.id = q.id and p.id = pq.pid.id and p.category = 'default' AND p.id = "+pid;
Query query=entityManagerUtil.getQuery(queryString);
List questionsList = query.getResultList();
return questionsList;
but it did not work.I mean I get nothing in the list.Can anybody point out my mistake.
question entity class
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Version;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Configurable;
#Configurable
#Entity
public class Question {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Version
#Column(name = "version")
private Integer version;
private String question;
private String category;
private boolean isDeleted;
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
parent entity class
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Configurable;
#Configurable
#Entity
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Version
#Column(name = "version")
private Integer version;
#ManyToOne
private Client cid;
public Client getCid() {
return cid;
}
public void setCid(Client cid) {
this.cid = cid;
}
private boolean isDeleted;
/* #ManyToOne
private Client cid;
public Client getCid() {
return cid;
}
public void setCid(Client cid) {
this.cid = cid;
}*/
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
private String name;
private String category;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
Commenters are confused by your classes, and this is a good indication that you might need to think about your design. suninsky has a good point that you may not need to have an entity class call ParentQuestion (unless ParentQuestion has extra data about the relationship, of course). Here are some typical questions I would be asking.
Does every Question have a Parent? If so then there should probably be a parent property on your Question class, mapped as #ManyToOne
Does every a Parent object have a set of Questions? If yes, then the Parent object should probably have a property named questions, the type of which is some kind of collection of Question objects.
I have a result set like this…
+--------------+--------------+----------+--------+
| LocationCode | MaterialCode | ItemCode | Vendor |
+--------------+--------------+----------+--------+
| 1 | 11 | 111 | 1111 |
| 1 | 11 | 111 | 1112 |
| 1 | 11 | 112 | 1121 |
| 1 | 12 | 121 | 1211 |
+--------------+--------------+----------+--------+
And so on for LocationCode 2,3,4 etc. I need an object (to be converted to json, eventually) as : List<Location>
Where the the hierarchy of nested objects in Location Class are..
Location.class
LocationCode
List<Material>
Material.class
MaterialCode
List<Item>
Item.class
ItemCode
Vendor
This corresponds to the resultset, where 1 location has 2 materials, 1 material(11) has 2 Items, 1 item(111) has 2 vendors. How do i achieve this? I have used AliasToBeanResultTransformer before, but i doubt it will be of help in this case.
I don't think there is a neat way to do that mapping. I'd just do it with nested loops, and custom logic to decide when to when to start building the next Location, Material, Item, whatever.
Something like this pseudo-code:
while (row = resultSet.next()) {
if (row.locationCode != currentLocation.locationCode) {
currentLocation = new Location(row.locationCode)
list.add(currentLocation)
currentMaterial = null
} else if (currentMaterial == null ||
row.materialCode != currentMaterial.materialCode) {
currentMaterial = new Material(row.materialCode)
currentLocation.add(currentMaterial)
} else {
currentMaterial.add(new Item(row.itemCode, row.vendorCode))
}
}