Created
June 9, 2021 12:20
-
-
Save Kshitij-Dhakal/962b2eeb898cd69704a9efd551c14b8e to your computer and use it in GitHub Desktop.
InsertOrUpdate.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.treeleaf.anydone.conversation.service.repo; | |
import com.google.common.collect.Lists; | |
import com.google.common.collect.Maps; | |
import com.treeleaf.SqlRepo; | |
import com.treeleaf.ex.TreeleafException; | |
import com.treeleaf.sql.JDBCException; | |
import com.treeleaf.sql.SqlDataSource; | |
import java.sql.Connection; | |
import java.sql.SQLException; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.stream.Collectors; | |
public class MatchRepoExample extends SqlRepo { | |
protected MatchRepoExample(SqlDataSource dataSource) { | |
super(dataSource); | |
} | |
//[{"pawan", "123"}, {"kshitij", ""},{"sanjit", "34}] | |
//["kshitij", "pawan"] | |
// [true, true, false] | |
public Map<CustomObj, Boolean> existsInDb(List<CustomObj> strList) throws TreeleafException { | |
try (Connection con = dataSource.getConnection()) { | |
Map<CustomObj, Boolean> existsInDb = Maps.newHashMap(); | |
for (CustomObj s : strList) { | |
var aBoolean = existsInDb(con, s); | |
existsInDb.put(s, aBoolean); | |
} | |
return existsInDb; | |
} catch (JDBCException | SQLException e) { | |
throw new TreeleafException(""); | |
} | |
} | |
//service | |
void saveOrUpdateService(List<CustomObj> strList) throws TreeleafException { | |
var booleans = existsInDb(strList); | |
List insetList; | |
List updateList; | |
booleans.entrySet() | |
.stream().collect(Collectors.groupingBy(Map.Entry::getValue)) | |
.forEach((aBoolean, entries) -> { | |
if (aBoolean) { | |
insetList.addall() | |
}else{ | |
updateList.addall() | |
} | |
}); | |
saveOrUpdate() | |
} | |
boolean saveOrUpdate(Map<CustomObj, Boolean> objList) { | |
Connection con = null; | |
try { | |
dataSource.getConnection(); | |
con.setAutoCommit(false); | |
} catch (JDBCException | SQLException e) { | |
e.printStackTrace(); | |
} | |
} | |
boolean save(List<CustomObj> objList) { | |
return false; | |
} | |
boolean update(List<CustomObj> objList) { | |
return false; | |
} | |
private Boolean existsInDb(Connection con, | |
CustomObj obj) throws TreeleafException { | |
String query = "SELECT COUNT(*) FROM table WHERE original_text=? and other_text=?"; | |
try (var pst = dataSource.prepareStatement(query, con)) { | |
pst.setString(1, obj.oText); | |
pst.setString(2, obj.cText); | |
return count(pst.executeQuery()) == 1; | |
} catch (JDBCException | SQLException e) { | |
throw new TreeleafException(""); | |
} | |
} | |
} | |
class CustomObj { | |
String oText; | |
String cText; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment