I have a database table in which there are already stored some data.
Now I want to have a Vaadin editable Table in my page with the data taken from database and when this Vaadin Table is updated (either add a row or edit the existing ones), the database should be updated aswell.
I was so close to that, but I realized I can't use just an INSERT query because the unique ID constraint is violated.
What can I do in order to achieve that? I really need your help!
The BeanItemContainer:
public BeanItemContainer createContainer() {
BeanItemContainer<Sct> beans = new BeanItemContainer<Sct>(Sct.class);
beans.addNestedContainerProperty("secti.sid");
beans.addNestedContainerProperty("secti.isa");
beans.addNestedContainerProperty("secti.order");
for (int i = 0; i < list.size(); i++) {
PS_SECTION section = list.get(i);
Long ps = section.getPS_SECTION();
String na = section.getNAME();
Long is = section.getISACTIVE();
Long or = section.getVORDER();
Object itemId = beans.addBean(new Sct(na, new BeanSect(ps, is, or)));
}
return beans;
}
Here is the save (update) button when clicked:
ClickListener saveListener = new ClickListener() {
private Long s4 = 0L;
#Override
public void buttonClick(ClickEvent event) {
Collection<?> itemIds = table.getItemIds();
Item item = null;
boolean isSaved = false;
PS_SECTION ps = null;
List<PS_SECTION> newlist = new ArrayList<PS_SECTION>();
int i = 0;
for(Object itemId : itemIds){
ps = new PS_SECTION();
item = table.getItem(itemId);
Long s1 = (Long) item.getItemProperty("ID").getValue();
String s2 = item.getItemProperty("SECTION").getValue().toString();
Long s3 = (Long) item.getItemProperty("ORDER").getValue();
Long s5 = 0L;
ps.setPS_SECTION(s1);
ps.setNAME(s2);
ps.setVORDER(s3);
ps.setISACTIVE(s4);
ps.setISGLOBAL(s5);
newlist.add(ps);
}
try {
// Here I call the query.
isSaved = dao.insertPsSections(newlist);
if (isSaved){
Notification.show("Success ");
unsavedChanges = false;
}
else if (!isSaved){
Notification.show("Problem");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Finally, the query:
public boolean insertPsSections(List<PS_SECTION> pssec) throws SQLException {
Boolean sv = false;
try {
this.setKeepConnOpen(true);
String insertsections = "INSERT INTO PS_SECTION"
+ "(PS_SECTION,NAME,ISACTIVE,ISGLOBAL,VORDER)"
+ "VALUES (?,?,?,?,?)";
for (PS_SECTION j : pssec){
Long section = j.getPS_SECTION();
String name = j.getNAME();
Long isa = j.getISACTIVE();
Long isg = j.getISGLOBAL();
Long order = j.getVORDER();
this.simpleUpdate(insertsections, false, section, name, isa, isg, order);
}
} finally {
this.doCommit();
this.closeConn(true);
sv=true;
}
return sv;
}
Related
I have a custom ArrayList and String ArrayList in my Android application. I am using one for-loop for adding custom list values to sqlite. I also remove rows in the custom ArrayList which will match with the value of the String ArrayList before adding to sqlite. I have to use two for-loops for this matter. Can I achieve this inside the sqlite adding loop?
ArrayList<String> localRefNoList = new ArrayList<>();
ArrayList<SynchronizDTO> arr_sync = new ArrayList<>();
public class SynchronizDTO {
private String userName;
private String referenceNo;
private String employeeNo;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getReferenceNo() {
return referenceNo;
}
public void setReferenceNo(String referenceNo) {
this.referenceNo = referenceNo;
}
public String getEmployeeNo() {
return employeeNo;
}
public void setEmployeeNo(String employeeNo) {
this.employeeNo = employeeNo;
}
}
for (int i = 0; i < arr_sync.size(); i++) {
for (String ss : localRefNoList) {
if (ss.equals(arr_sync.get(i).getReferenceNo().trim())) {
arr_sync.remove(i);
}
}
}
for (int i = 0; i < arr_sync.size(); i++) {
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.userName, arr_sync.get(i).getUserName().trim());
cv.put(DatabaseHelper.referenceNo, arr_sync.get(i).getReferenceNo().trim());
cv.put(DatabaseHelper.employeeNo, arr_sync.get(i).getEmployeeNo().trim());
try {
restoreLogRes = db.insertOrThrow(DatabaseHelper.tbl_sms, null, cv);
} catch (Exception ex) {
}
}
You can add a flag variable to do this in one go. And it will be much more intuitional if you do it on the removing loop rather than sqlite adding loop. Here I am optimizing a little bit. Also remember don't call for (int i = 0; i < arr_sync.size(); i++) here. It will calculate list size again and again. Rather do this :
int length = arr_sync.size();
for (int i = 0; i < length; i++) {
boolean flag = true;
for (String ss : localRefNoList) {
if (ss.equals(arr_sync.get(i).getReferenceNo().trim())) {
arr_sync.remove(i);
flag = false;
break;
}
}
if(flag){
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.userName, arr_sync.get(i).getUserName().trim());
cv.put(DatabaseHelper.referenceNo,
arr_sync.get(i).getReferenceNo().trim());
cv.put(DatabaseHelper.employeeNo, arr_sync.get(i).getEmployeeNo().trim());
try {
restoreLogRes = db.insertOrThrow(DatabaseHelper.tbl_sms, null, cv);
} catch (Exception ex) {
}
}
}
I have a java method with insert and select like that:
#Override
public Page<ApprovalProcessEntity> getApprovalProcess(int page, int size, String approvalNum, String approvalType, int approvalStatus, Date start, Date end) {
//jpa inseart
checkAndInsertApprovalProcess();
//querydsl select
return getApprovalProcess2(page, size, approvalNum, approvalType, approvalStatus, start, end);
}
#Override
#Transactional(rollbackFor = Exception.class)
public void checkAndInsertApprovalProcess() {
List<Task> list = taskService.createTaskQuery().taskCandidateOrAssigned(curUserId()).list();
String confirmVar = "IS_CONFIRM";
List<ApprovalProcessEntity> entities = new ArrayList<>();
Set<String> processInstanceIds = new HashSet<>();
for (Task task : list) {
processInstanceIds.add(task.getProcessInstanceId());
}
Map<String, ApprovalApplyEntity> map = approvalApplyDao.findAllByProcessInstanceIdIn(processInstanceIds).stream().collect(Collectors.toMap(ApprovalApplyEntity::getProcessInstanceId, k -> k));
for (Task task : list) {
Object confirm = taskService.getVariable(task.getId(), confirmVar);
if (confirm != null) {
continue;
}
taskService.setVariable(task.getId(), confirmVar, true);
ApprovalProcessEntity entity = new ApprovalProcessEntity();
String processInstanceId = task.getProcessInstanceId();
ApprovalApplyEntity apply = map.get(processInstanceId);
entity.setApprovalStatus(1);
entity.setCurNode(task.getName());
entities.add(entity);
}
approvalProcessDao.saveAll(entities);
}
Page<ApprovalProcessEntity> getApprovalProcess2(int page, int size, String approvalNum, String approvalType, int approvalStatus, Date start, Date end) {
String userId = curUserId();
QApprovalProcessEntity qEntity = QApprovalProcessEntity.approvalProcessEntity;
JPAQuery<ApprovalProcessEntity> jpaQuery = queryFactory
.selectFrom(qEntity)
.where(qEntity.createTime.between(start, end))
.where(qEntity.createPerson.eq(userId));
if (StrUtil.isNotBlank(approvalNum)) {
jpaQuery = jpaQuery.where(qEntity.approvalNum.eq(approvalNum));
}
if (StrUtil.isNotBlank(approvalType)) {
jpaQuery = jpaQuery.where(qEntity.approvalType.eq(approvalType));
}
if (approvalStatus != -1) {
jpaQuery = jpaQuery.where(qEntity.approvalStatus.eq(approvalStatus));
}
PageRequest pr = PageRequest.of(page, size);
List<ApprovalProcessEntity> entities = jpaQuery.offset(pr.getOffset()).limit(pr.getPageSize()).fetch();
return new PageImpl<>(entities, pr, jpaQuery.fetchCount());
}
if some task haven't be confirmed,insert a new entity in to table;
then select data from this table;
if I use the following code,
when I had a new task, it can insert successfully,
but can't select data immediately,
if call getApprovalProcess() again, getApprovalProcess2() method work well,
so how can I select data immediately after insert;
meanwhile, if i change getApprovalProcess2() likeļ¼
Page<ApprovalProcessEntity> getApprovalProcess2(int page, int size, String approvalNum, String approvalType, int approvalStatus, Date start, Date end) {
return approvalProcessDao.findAll(PageRequest.of(page, size));
}
then create a new task and call getApprovalProcess() method again()
it can select data immediately, work well
but actually what I want is Previous Impl,so what should I do that can make it work;
I am trying to use the user's selection of a JRadioButton as part of a SELECT query for a derby database. For some reason, when I click the search button (called diffSearchbtn), nothing happens. What should be happening is that the SELECT query puts all the entries that match the criteria of the radio button into a JTable on a panel called dispPanel.
Here is the code for the method that assigns a string based on what button the user clicks.
private String tagValid()
{
String diff = "";
if (dEasybtn.isSelected())
{
diff = "EASY";
System.out.println("easy");
}
else if (dMedbtn.isSelected())
{
diff = "MEDIUM";
System.out.println("medium");
}
else if (dHardbtn.isSelected())
{
diff = "HARD";
System.out.println("hard");
}
else
{
diff = null;
}
return null;
}
Here is the code that is meant to display the form:
private void diffSearchbtnActionPerformed(java.awt.event.ActionEvent evt) {
if(tagValid()!=null)
{
String q = String.format("Select* from Gabby.PData where DIFFICULTY = '%d'", tagValid());
ResultSet res = Backend.query(q);
guiTable.setModel(DbUtils.resultSetToTableModel(res));
int counter = 3;
try
{
while (res.next()) {
counter++;
System.out.println("increasing counter");
}
}
catch (SQLException ex) {
Logger.getLogger(WikiPlantGUI.class.getName()).log(Level.SEVERE, null, ex);
}
if (counter == 0)
{
basePanel.removeAll();
basePanel.add(NoMatchPanel);
basePanel.repaint();
basePanel.revalidate();
}
else
{
basePanel.removeAll();
basePanel.add(dispPanel);
basePanel.repaint();
basePanel.revalidate();
}
}
}
Here is the code from the class Backend:
public static ResultSet query(String q)
{
try {
System.out.println("a query");
Statement stat = myConObj.createStatement();
ResultSet res = stat.executeQuery(q);
return res;
}
catch (SQLException e)
{
e.printStackTrace(); // tells what the error is
return null; // returns nothing
}
}
GUI screenshot
There are no error messages, and the program otherwise runs perfectly. Any idea on what's going wrong?
I need to display all the columns from the table in java. So far I have tried resultSet java object but it is not working for me
public class dbtest {
public static Session session = null;
public ArrayList < String > ColValue() throws IOException {
// TODO Auto-generated method stub
FileReader reader = new FileReader("Configuration\\Config.properties");
Properties p = new Properties();
p.load(reader);
String serverIp = p.getProperty("ServerIp");
String keyspace = p.getProperty("ServerPwd");
Cluster cluster = Cluster.builder().addContactPoints(serverIp).withCredentials("user", "password").build();
session = cluster.connect(server);
String query = null;
String cqlStatement = "select * from table_name";
ArrayList < String > casVal1 = new ArrayList < >();
for (Row row: session.execute(cqlStatement)) {
if (!casVal1.contains(query)) {
casVal1.add(query);
}
}
System.out.println(casVal1.size());
System.out.println(casVal1);
return (casVal1);
}
}
Need all the columns in results as outcomes.
You can get the column via the ResultSet.getColumnDefinitions Method
com.datastax.driver.core.ResultSet result = xxxxx;
for (Definition definition : result.getColumnDefinitions()) {
String name = definition.getName();
}
I wanted to harvest some data on specific apps in
Google play marketplace.
I have used this unofficial API:
https://code.google.com/p/android-market-api/
Here is my code, that basically gets list of apps' names
and try to fetch other data on each app:
public void printAllAppsData(ArrayList<AppHarvestedData> dataWithAppsNamesOnly)
{
MarketSession session = new MarketSession();
session.login("[myGamil]","[myPassword]");
session.getContext().setAndroidId("dead00beef");
final ArrayList<AppHarvestedData> finalResults = new ArrayList<AppHarvestedData>();
for (AppHarvestedData r : dataWithAppsNamesOnly)
{
String query = r.name;
AppsRequest appsRequest = AppsRequest.newBuilder()
.setQuery(query)
.setStartIndex(0).setEntriesCount(10)
//.setCategoryId("SOCIAL")
.setWithExtendedInfo(true)
.build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
List<App> apps = response.getAppList();
for (App app : apps) {
AppHarvestedData r = new AppHarvestedData();
r.title = app.getTitle();
r.description = app.getExtendedInfo().getDescription();
String tmp = app.getExtendedInfo().getDownloadsCountText();
tmp = tmp.replace('<',' ').replace('>',' ');
int indexOf = tmp.indexOf("-");
tmp = (indexOf == -1) ? tmp : tmp.substring(0, indexOf);
r.downloads = tmp.trim();
r.rating = app.getRating();
r.version = app.getVersion();
r.userRatingCount = String.valueOf(app.getRatingsCount());
finalResults.add(r);
}
}
});
session.flush();
}
for(AppHarvestedData res : finalResults)
{
System.out.println(res.toString());
}
}
}
Should I realyy call session.flush(); at this point?
all my quesries return empty collection as a result,
even though I see there are some names as input.
It works fine when I send only one hard coded app name as a query.
session.flush() close you session
you should open session for each query. pay attention the user can be locked for few minutes so you should have many users to to those queries.
if you have the AppId you should use that query:
String query = r.name;
AppsRequest appsRequest = AppsRequest.newBuilder()
.setAppId("com.example.android")
.setWithExtendedInfo(true)
.build();
session.append(appsRequest, new Callback<AppsResponse>() {
#Override
public void onResult(ResponseContext context, AppsResponse response) {
List<App> apps = response.getAppList();
for (App app : apps) {
AppHarvestedData r = new AppHarvestedData();
r.title = app.getTitle();
r.description = app.getExtendedInfo().getDescription();
String tmp = app.getExtendedInfo().getDownloadsCountText();
tmp = tmp.replace('<',' ').replace('>',' ');
int indexOf = tmp.indexOf("-");
tmp = (indexOf == -1) ? tmp : tmp.substring(0, indexOf);
r.downloads = tmp.trim();
r.rating = app.getRating();
r.version = app.getVersion();
r.userRatingCount = String.valueOf(app.getRatingsCount());
finalResults.add(r);
}
}
});
session.flush();
}
if you want to download also screenshoot or images you should call this query:
GetImageRequest? imgReq; imgReq = GetImageRequest?.newBuilder().setAppId(appId).setImageUsage(AppImageUsage?.SCREENSHOT).setImageId("0").build();
session.append(imgReq, new Callback<GetImageResponse>() {
#Override public void onResult(ResponseContext? context, GetImageResponse? response) {
Log.d(tag, "------------------> Images response <----------------"); if(response != null) {
try {
//imageDownloader.download(image, holder.image, holder.imageLoader);
Log.d(tag, "Finished downloading screenshot 1...");
} catch(Exception ex) {
ex.printStackTrace();
}
} else {
Log.e(tag, "Response was null");
} Log.d(tag, "------------> End of Images response <------------");
}
});