I need to retrieve all the account numbers of the transaction table/object which given below. Using mysql for database.
Entity Class
public class Transaction implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "cr_account_ref")
private String crAccountRef;
#Column(name = "dr_account_ref")
private String drAccountRef;
#Column(name = "amount")
private String amount;
// getters and setters.
}
My Table
| cr_account_ref | dr_account_ref | amount |
|----------------------------------------------------------
|1000001 |2000009 | 100 |
|1000002 |2000008 | 500 |
|1000001 |2000006 | 100 |
|1000003 |2000004 | 500 |
|1000005 |2000008 | 611 |
|1000001 |2000009 | 300 |
|1000002 |2000004 | 120 |
-----------------------------------------------------------
What i need is, distinct of all the account numbers(both debit and credit.).
| cr_account_ref |
|----------------------
|1000001 |
|1000002 |
|1000003 |
|1000005 |
|2000004 |
|2000006 |
|2000008 |
|2000009 |
-----------------------
This is easy with pure jdbc, but i need to do the this with HQL.
Related
I'm trying to make a todo application on Spring. It's almost finished but I got a problem. I need to filter todos by user id and select them which is in the between given dates. I've created a method for this in my TodoRepository. But when I send the request to the url, it gives me empty array.
Here's the repository class:
All methods work fine except the one I mentioned btw.
#Repository
public interface TodoRepository extends JpaRepository<Todo, Long> {
List<Todo> findTodosByUserId(Long id);
List<Todo> findTodosByUserIdOrderByDateAsc(String id);
List<Todo> findAllByDateBetween(Date date, Date date2);
List<Todo> findTodosByDateBetweenAndUserId(Date date, Date date2, Long id);
}
That's the method i use in the TodoService class:
#Service
public class TodosService {
#Autowired
TodoRepository todoRepository;
//other methods..
public List<Todo> filterTodosByUserId(FilterTodoByUserDto dto){
Date date1 = dto.getDate1();
Date date2 = dto.getDate2();
Long id = dto.getId();
return todoRepository.findTodosByDateBetweenAndUserId(date1, date2, id);
}
}
FilterTodoByUserDto class:
public class FilterTodoByUserDto {
private Long id;
private Date date1;
private Date date2;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDate1() {
return date1;
}
public void setDate1(Date date1) {
this.date1 = date1;
}
public Date getDate2() {
return date2;
}
public void setDate2(Date date2) {
this.date2 = date2;
}
#Override
public String toString() {
return "FilterTodoByUserDto{" +
"id=" + id +
", date1=" + date1 +
", date2=" + date2 +
'}';
}
}
And lastly, controller class:
#RestController
#RequestMapping("/api")
public class TodoController {
#Autowired
private TodosService todosService;
//other methods..
#GetMapping("user/todos/filter")
public List<Todo> filterTodosById(#RequestBody FilterTodoByUserDto dto){
List<Todo> todos = todosService.filterTodosByUserId(dto);
return todos;
}
//other methods..
}
Request body that i sent with postman:
{"userId":"1", "date1":"2021-01-01", "date2":"2000-01-01"}
Database output:
mysql> select * from todos;
+----+----------------------------+-------------+-------------+---------+
| id | date | description | todo_status | user_id |
+----+----------------------------+-------------+-------------+---------+
| 1 | 2012-12-12 00:00:00.000000 | deneme | TODO | 2 |
| 2 | 2010-10-10 00:00:00.000000 | deneme2 | TODO | 2 |
| 3 | 2010-01-01 00:00:00.000000 | deneme5 | DONE | 1 |
| 4 | 2010-01-01 00:00:00.000000 | deneme | DONE | 1 |
| 5 | 2010-01-01 00:00:00.000000 | deneme | DONE | 1 |
| 6 | 2010-01-01 00:00:00.000000 | deneme | DONE | 1 |
| 7 | 2010-01-01 00:00:00.000000 | deneme | DONE | 1 |
| 8 | 2010-01-01 00:00:00.000000 | deneme | DONE | 1 |
| 9 | 2010-01-01 00:00:00.000000 | deneme | DONE | 2 |
+----+----------------------------+-------------+-------------+---------+
9 rows in set (0,01 sec)
Change your request json like this:
{
"id": "1",
"date1": "2000-01-01",
"date2": "2021-01-01"
}
Your fields in your DTO model should match your json fields. (userId -> id)
BETWEEN returns true if the value of date is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression. (.. date BETWEEN date1 AND date2)
You are getting empty array due to your postman request is logically wrong. When BETWEEN use date1 must be the minimum value and date2 must be the maximum value.
ex: The following date example uses the BETWEEN condition to retrieve values within a date range.
SELECT *
FROM todos
where user_id=1
and date between '2000-01-01' and '2021-01-01';
Above BETWEEN SQL would be equivalent to the following SELECT statement:
SELECT *
FROM todos
where user_id=1
and date >= '2000-01-01' and date<= '2021-01-01';
I'm trying to fetch the count of all individual records from mysql database using hibernate and I have to store it in a map collection. How to do this?
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();
String hql = "select attendencestatus ,COUNT(attendencestatus) from studentattendance group by attendencestatus ";
Query query = session.createQuery(hql);
tx.commit();
} catch (HibernateException he) {
he.printStackTrace();
tx.rollback();
}
--------------------------------------
| ID |CountryName| CurrencyName|
|_________|___________|______________|
| 1 | India | Rupees |
| 2 | India | Rupees |
| 3 | India | Rupees |
| 4 | Usa | dollar |
| 5 | dubai | AED |
| 6 | Germany | Euro |
|--------------------------------------
String hql="select anyColmnName from entity;
Query query = session.createQuery(hql);
List<string> list=query.list();
int countOfRecords=Collections.frequency(list, value)
Example
String hql="select countryName from Revenue;
Query query = session.createQuery(hql);
List<string> list=query.list();
int countOfRecords=Collections.frequency(list, "India")
I'm working on Spring + Spring Data JPA example. In this example I was running my test case to get the Actor by FirstName and LastName, but when I run the Test case, I see the following error:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring/database-context.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: jpa-mysql-db] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 25 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: jpa-mysql-db] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:951)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:881)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:340)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:319)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1641)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
... 40 more
Caused by: org.hibernate.MappingException: property mapping has wrong number of columns: com.sakila.entity.Film.specialFeatures type: object
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:600)
at org.hibernate.mapping.RootClass.validate(RootClass.java:265)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:489)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:878)
... 45 more
I am using the sakila database from the link: https://dev.mysql.com/doc/index-other.html
mysql> desc film;
+----------------------+---------------------------------------------------------------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+---------------------------------------------------------------------+------+-----+-------------------+-----------------------------+
| film_id | smallint(5) unsigned | NO | PRI | NULL | auto_increment |
| title | varchar(255) | NO | MUL | NULL | |
| description | text | YES | | NULL | |
| release_year | year(4) | YES | | NULL | |
| language_id | tinyint(3) unsigned | NO | MUL | NULL | |
| original_language_id | tinyint(3) unsigned | YES | MUL | NULL | |
| rental_duration | tinyint(3) unsigned | NO | | 3 | |
| rental_rate | decimal(4,2) | NO | | 4.99 | |
| length | smallint(5) unsigned | YES | | NULL | |
| replacement_cost | decimal(5,2) | NO | | 19.99 | |
| rating | enum('G','PG','PG-13','R','NC-17') | YES | | G | |
| special_features | set('Trailers','Commentaries','Deleted Scenes','Behind the Scenes') | YES | | NULL | |
| last_update | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+----------------------+---------------------------------------------------------------------+------+-----+-------------------+-----------------------------+
13 rows in set (0.00 sec)
Film.java
#Entity
#NamedQuery(name="Film.findAll", query="SELECT f FROM Film f")
public class Film implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="film_id")
private int filmId;
#Lob
private String description;
#Column(name="last_update")
private Timestamp lastUpdate;
private int length;
private String rating;
#Temporal(TemporalType.DATE)
#Column(name="release_year")
private Date releaseYear;
#Column(name="rental_duration")
private byte rentalDuration;
#Column(name="rental_rate")
private BigDecimal rentalRate;
#Column(name="replacement_cost")
private BigDecimal replacementCost;
#Column(name="special_features")
private Object specialFeatures;
private String title;
//bi-directional many-to-one association to Language
#ManyToOne
#JoinColumn(name="language_id")
private Language language1;
//bi-directional many-to-one association to Language
#ManyToOne
#JoinColumn(name="original_language_id")
private Language language2;
//bi-directional many-to-one association to FilmActor
#OneToMany(mappedBy="film")
private List<FilmActor> filmActors;
//bi-directional many-to-one association to FilmCategory
#OneToMany(mappedBy="film")
private List<FilmCategory> filmCategories;
//bi-directional many-to-one association to Inventory
#OneToMany(mappedBy="film")
private List<Inventory> inventories;
// Assume respective setters and getters are present
}
Please let me know if need any other info.
If you use maven, put the xml file on resource folder.
Else, add the folder which contain the xml file to source folder.
Good luck
please remove The Object
and try that, it will work
#Column(name = "special_features", columnDefinition = "set('Trailers','Commentaries','Deleted Scenes','Behind the Scenes')")
private String specialFeatures;
fund_allocation_template
template_id | template_name | status |
1 Mega Lotto 1
2 EZ-2 1
fund_allocation_item
| item_id | item_name | status |
1 Charity 1
2 Operation Expenses 1
3 Food Allowance 1
4 Transportation Allowance 1
| 5 | Calamity Victims | 1 |
r_template_item
| template_id | item_id | item_percentage |
1 1 45.00
1 2 55.00
2 1 40.00
2 2 46.00
//FundAllocationTemplate.java(domain)
private Integer templateID;
private String templateName;
private Integer templateStatus
//FundAllocationItem.java(domain)
private Integer itemID;
private String itemName;
private Integer itemStatus
<resultMap id="fundTemplate" type="FundAllocationTemplate">
<id property="fundTemplateID" column="template_id" />
<result property="fundTemplateName" column="template_name" />
<result property="fundTemplateStatus" column="status" />
//Association for Status
</resultMap>
<resultMap id="fundItem" type="FundAllocationItem">
<id property="fundItemID" column="item_id" />
<result property="fundItemName" column="item_name" />
<result property="fundItemStatus" column="status" />
//Association for Status
</resultMap>
FORM
private Integer templateID;
private String templateName;
private BigDecimal totalPercentage;
private Integer status;
Form Or Page Output
| Allocation Template Name | Fund Template Percentage | Status |
| Mega Lotto | 100% | Active |
| EZ-2 | 86% | Active |
Question: How can I be able to show the total percentage of every Fund Template with the given domain and table design?
Use the following query:
select T.template_name,SUM(R.item_percentage) as Fund_Template_Percentage,
(CASE T.status WHEN 1 THEN "Active" ELSE "NOT Active" END) STATUS
from fund_allocation_template T, r_template_item R
where T.template_id=R.template_id
GROUP BY R.template_id;
The application allows users to select certain keywords (which we monitor the TwitterStream for)
Each Keyword contains a list of the tweet IDs that contain its keyword.
public class Keyword extends Model {
#Id
int id;
String keyword;
#ManyToMany
public List<Tweet> tweets = new ArrayList();
}
public class Tweet extends Model {
#Id
int id;
TimeStamp datetime;
}
I'd like to get some data on how each keyword performs each day by select count(*), datetime grouping them by day. The following SQL query will accomplish what I need.
select datetime, count(*) from tweet t left outer join keyword_tweet on t.id=keyword_tweet.tweet_id group by cast(t.datetime as date) having t.datetime > '2014-02-02';
+---------------------+----------+
| datetime | count(*) |
+---------------------+----------+
| 2014-02-02 13:27:45 | 1 |
| 2014-02-08 05:14:04 | 2 |
| 2014-02-09 08:34:31 | 1 |
| 2014-02-12 12:42:02 | 1 |
| 2014-02-13 06:00:09 | 2 |
| 2014-02-14 00:47:04 | 2 |
| 2014-02-15 07:26:30 | 6 |
| 2014-02-16 01:00:00 | 21 |
| 2014-02-17 00:06:50 | 916 |
| 2014-02-18 18:08:56 | 1 |
| 2014-02-19 01:28:40 | 1 |
| 2014-02-24 16:45:11 | 1 |
| 2014-02-26 14:43:54 | 4 |
| 2014-02-27 08:24:09 | 9 |
| 2014-02-28 05:08:16 | 411 |
+---------------------+----------+
How do I select * from Tweets where Tweet.id is IN Keyword.tweets ?
Also how in Ebean would I get a List that only contains Dates, and Count(*)?
Thanks guys!
You can use something along these lines:
Keyword targetKeyword = Keyword.find.byId(1L);
List<Tweets> foundTweets = new ArrayList<Tweets>();
for(Tweet tw : Tweets.find.all()) {
if(targetKeyword.tweets.contains(tw))
foundTweets.add(tw);
}
return foundTweets;
This code will return all tweets contained in keyword id number 1. You can place this in a function passing the keyword id you want instead of 1L.