how do I get spring to recognize the first capital letter using postgresql - spring

I have a question how I can do so that in spring my table is recognized with the first capital letter, is made in postgresql
#Entity
#Table(name="System_user")
public class Dashboard {
#Id
#Column(name = "username")
String username;
get..
set...
}
it generates an error and I change it as shown below
#Table("\"System_user\"")
but he still doesn't recognize me

As we discussed in the comments, the issue was in dialect.
Latest dialect for now - org.hibernate.dialect.PostgreSQL95Dialect
The issue solved this dialect:
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
Answer to your HQL-code:
I would suggest using TypedQuery as it returns not just a list, but list of your object.
Furthermore, u are using the same session to transfer data. This is bad for the program. Always do like Open session - transfer data - close session.
Try this code:
public List<Vw_dh_assay> listAssayReport(double year, String project_id, String hole_id) {
List<Vw_dh_assay> list = new ArrayList<>();
Session session;
try {
session = this.sessionFactory.openSeesion();
TypedQuery<Vw_dh_assay> query = session.createQuery("from Vw_dh_assay where year = :year AND project_id = :project_id AND hole_id = :hole_id", Player.class);
query.setParameter("year", year);
query.setParameter("project_id", project_id);
query.setParameter("hole_id", hole_id);
list = query.getResultList();
System.out.println(list);
session.clear();
session.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}

this is my code DAO #Antonio112009
#Override
public List<Vw_dh_assay> listAssayReport(double year, String project_id, String hole_id) {
Session session = this.sessionFactory.getCurrentSession();
String query = ("SELECT DISTINCT year,project_id,hole_id from "
+ "Vw_dh_assay where year = :year AND project_id = :project_id AND hole_id = :hole_id");
List result = session.createQuery(query).setParameter("year", year).setParameter("project_id", project_id)
.setParameter("hole_id", hole_id).list();
System.out.println(result);
return result;
}

Related

Mybatis + Spring Boot : #Update is not working

I am trying to do an update using #update annotation. The query triggers fine without any exceptions but method returns 0 every time (0 row updated). No update is happening in the db. and same query is working fine from SQLdeveloper tool.
Using Oracle db.
#Update(
"UPDATE extra.EMMT SET CASE_STATUS = #{updateBean.CASE_STATUS}, CASE_STATUS_TimeStmp = #{updateBean.CASE_STATUS_TimeStmp} WHERE T_TimeStmp >= #{updateBean.LAST_T_TimeStmp} AND T_TimeStmp <= #{updateBean.T_TimeStmp} AND T_NO = #{updateBean.T_NO} AND EM_NO = #{updateBean.EM_NO}"
)
public long update(#Param("updateBean") EMMT updateBean);
"EMMT updateBean" is class has same members as the columns the table EMMT.
and I also tried creating two different sessions one for update and other is for insert, but didn't help much.
Session config.
#Bean(name = "updatesession")
public SqlSessionFactory sqlSessionFactoryupdate() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
SqlSessionFactory sqlSessionFactory = factoryBean.getObject();
sqlSessionFactory.getConfiguration().setJdbcTypeForNull(JdbcType.NULL);
sqlSessionFactory.getConfiguration().setDefaultStatementTimeout(15);
sqlSessionFactory.getConfiguration().addMappers("com.xyz.myapp.mapper");
return sqlSessionFactory;
}
Using Mybatis-spring - 2.2.0
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
Any help would be apricated.
Thanks.
EXAMPLE -
configuration for sqlSession is given above.
bean class.
class justForUpdate {
String CASE_STATUS;
String EM_NO ;
Timestamp T_TimeStmp;
Long T_NO ;
Timestamp CASE_STATUS_TimeStmp;
Timestamp LAST_T_TimeStmp;
}
service class
updateservice {
#Autowired
private SqlSessionFactory sessions;
public void work() {
//obj of justForUpdate = auth
//or can pass list of justForUpdate objs.
try(SqlSession session = sessions.openSession(true)){
Update_mapper upd = session.getMapper(Update_mapper.class);
long val = upd.update(auth);
System.out.print(">>>>>>>>> "+val);
}
}
}
Update_Mapper
#Mapper
public interface Update_mapper {
#Update(
"UPDATE extra.EMMT SET CASE_STATUS = #{updateBean.CASE_STATUS}, CASE_STATUS_TimeStmp = #{updateBean.CASE_STATUS_TimeStmp} WHERE T_TimeStmp >= #{updateBean.LAST_T_TimeStmp} AND T_TimeStmp <= #{updateBean.T_TimeStmp} AND T_NO = #{updateBean.T_NO} AND EM_NO = #{updateBean.EM_NO}"
)
public long update(#Param("updateBean") EMMT updateBean);
}
For anyone else who might bump into this same stupid problem.
the quick fix was using "TRIM()" in my query with column name.
Some columns were defined as 40 bytes. hence containing numbers of spaces.
#Update(
"UPDATE extra.EMMT SET CASE_STATUS = #{updateBean.CASE_STATUS}, CASE_STATUS_TimeStmp = #{updateBean.CASE_STATUS_TimeStmp} WHERE T_TimeStmp >= #{updateBean.LAST_T_TimeStmp} AND T_TimeStmp <= #{updateBean.T_TimeStmp} AND TRIM(T_NO) = #{updateBean.T_NO} AND TRIM(EM_NO) = #{updateBean.EM_NO}")
public long update(#Param("updateBean") EMMT updateBean);
}

Get all attributes from Active Directory using Spring LdapTemplate

I have a Spring Boot application that uses LDAP to authenticate the users. For the users, I am mapping the attributes from AD and populating the values like the user's first name, last name, department, email, telephone, and also the image. However, I am unable to get the employee number from the attributes.
When I check the attributes using the tool Active Directory explorer, I am able to see 88 attributes per entry. However, when I print every attribute from the context using this code,
#Bean
public UserDetailsContextMapper userDetailsContextMapper() {
return new LdapUserDetailsMapper() {
#Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
String email = ctx.getStringAttribute("mail");
String department = ctx.getStringAttribute("department");
String empNumber = ctx.getStringAttribute("employeeNumber");
System.out.println(empNumber); // this prints null
System.out.println(ctx.attributeExists("employeeNumber")); // this prints false
byte[] value= (byte[])ctx.getObjectAttribute("thumbNailPhoto");
BASE64Encoder base64Encoder = new BASE64Encoder();
StringBuilder imageString = new StringBuilder();
imageString.append("data:image/jpg;base64,");
imageString.append(base64Encoder.encode(value));
String image = imageString.toString();
Attributes attributes = ctx.getAttributes();
NamingEnumeration<? extends Attribute> namingEnumeration = attributes.getAll();
try {
while(namingEnumeration.hasMore()){
/*this loop prints 75 attributes but employeeNumber attribute is missing along with some other attributes*/
Attribute attribute = namingEnumeration.next();
System.out.println(attribute);
}
} catch (NamingException e) {
e.printStackTrace();
}
CustomUserDetails userDetails = (CustomUserDetails)userService.loadUserByUsername(username);
userDetails.setImage(image);
userDetails.setEmail(email);
userDetails.setDepartment(department);
return userDetails;
}
};
}
only 75 attributes are printed. Why is it that some of the attributes are not retrieved? how can i access those attributes?
I think you need to expand array elements like memberof.
Try this.. it may help.
Attribute attribute = namingEnumeration.next();
System.out.println(attribute);
System.out.println(attribute.size());
if size is greater than one.. expand it again

How can I insert a "null" timestamp with Spring JDBC Framework into a DB2 database

I created a Java web application, in which I use the Spring JDBC Framework, in order to write my queries for the DB2 database. So far all the queries are working excellent.
I tried today to create an INSERT query for a table I have in my database. The query is really straight forword, it works as DB2 query and it looks like this:
INSERT INTO MYDB.USERSUBSCRIPTION (USERNAME, SUBSCRIPTIONDATETIME, UNSUBSCRIPTIONDATETIME)
VALUES('JamesTheBoss', '2017-07-07 07:07:07.007', null);
In my Java class I created the following methods:
private Timestamp getCurrentDateTimeInTimeStamp() {
LocalDateTime currentDateAndTime = LocalDateTime.now();
currentDateAndTime.format(DateTimeFormatter.ofPattern("yyy-MM-dd HH:MM:SS.mm")).replaceAll("T", " ");
Timestamp timestamp = Timestamp.valueOf(currentDateAndTime);
return timestamp;
}
public void insertNewUserToDatabase(String username){
Timestamp timestamp = getCurrentDateTimeInTimeStamp();
String SQL = "INSERT INTO MYDB.USERSUBSCRIPTION (USERNAME, SUBSCRIPTIONDATETIME, UNSUBSCRIPTIONDATETIME) " +
"VALUES(?, ?, ?)";
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
jdbcTemplateObject.update(SQL,new Object[] { username, timestamp, null});
}
My first query was the following:
public List<UserSubscription> getAllUserSubscriptions() throws SQLException {
String SQL = "SELECT * FROM MYDB.USERSUBSCRIPTION";
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
List<UserSubscription> userSubscription = jdbcTemplateObject.query(SQL, new UserSubscriptionMapper());
return userSubscription;
}
and it works fine, as all other queries I wrote also do.
When I try to insert "null" as a Timestamp Parameter in the query, I become an exception.
How can I insert a "null" value for a Timestamp by using the Spring JDBC Framework?
I would really appreciate having a feedback.
I have been debbuging for a while and I found out that I can hardcode a null in my query and then the query works fine.
With a hardcoded "null" the query looks like this:
public void insertNewUserToDatabase(String username){
Timestamp timestamp = getCurrentDateTimeInTimeStamp();
String SQL = "INSERT INTO MYDB.USERSUBSCRIPTION (USERNAME, SUBSCRIPTIONDATETIME, UNSUBSCRIPTIONDATETIME) " +
"VALUES(?, ?, null)"; // <--- Hard Coded "null"
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
jdbcTemplateObject.update(SQL,new Object[] { username, timestamp});
}
When this query is executed, I become a new record in DB2 Database with a "null" value for column "UNSUBSCRIPTIONDATETIME".

Getting reasonable performance from a parameterized query in Spring JDBC template

I am trying to execute a very simple query from Spring JDBCTemplate. I am retrieving one attribute from a record that is identified by primary key. The entirely of the code is shown below. When I do this with a query constructed by concatenation (dangerous and ugly, and currently uncommented) it executes in 0.1 second. When I change my comments and use the parameterized query it executes in 50 seconds. I would much prefer to get the protection that comes with the parameterized query, however 50 seconds seems like a steep price to pay. Any hints how this could be made more reasonable.
public class JdbcEventDaoImpl {
private static JdbcTemplate jtemp;
private static PreparedStatement getJsonStatement;
private static final Logger logger = LoggerFactory.getLogger(JdbcEventDaoImpl.class);
#Autowired
public void setDataSource(DataSource dataSource) {
JdbcEventDaoImpl.jtemp = new JdbcTemplate(dataSource);
}
public String getJdbcForPosting(String aggregationId){
try {
return (String) JdbcEventDaoImpl.jtemp.queryForObject("select PostingJson from PostingCollection where AggregationId = '" + aggregationId + "'", String.class);
//return (String) JdbcEventDaoImpl.jtemp.queryForObject("select PostingJson from PostingCollection where AggregationId = ?", aggregationId, String.class);
} catch (EmptyResultDataAccessException e){
return "Not Available";
}
}
}

In Hibernate using Lazy loading instead of eager loading

I am working on a Spring-MVC application in which the user can register products and productImages. Now there are 3 tables, User, Product, ProductImages. It is not always necessary to pull all the productImages until and unless the user explicitly goes into the product, where there is a modal, and the user can then select the images to load.
So I thought of using LazyLoading instead of EagerFetching. But I get lazyLoadException with that. So I opened a session manually in both Product and ProductImages, and I get a ObjectNotFound Exception. The problem is, productImages has a foreign key relation with product, so I must save product first before saving its images, and that is where I am having the problem. Kindly suggest me how to use lazy load in this situation. Error log and code goes below :
Error log :
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.WirTauschen.model.ProductImage#1150]
org.hibernate.internal.SessionFactoryImpl$1$1.handleEntityNotFound(SessionFactoryImpl.java:253)
com.WirTauschen.dao.ProductBasicDaoImpl.updateProduct(ProductBasicDaoImpl.java:50)
Controller :
#RequestMapping(value = "/product/addimages", method = RequestMethod.POST)
public #ResponseBody String addProductImages(#RequestParam("productImages") MultipartFile[] uploadedFiles){
if(uploadedFiles != null && uploadedFiles.length>0) {
for (MultipartFile uploadedFile : uploadedFiles) {
try {
if (!(uploadedFile.isEmpty())) {
imagesList.add(uploadedFile.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
return "image failed to upload";
}
}
}
return "done";
}
#RequestMapping(value="/product/add",method = RequestMethod.POST)
public String addProduct(#ModelAttribute("product") ProductBasic productBasic,Model model){
model.addAttribute("product", new ProductBasic());
productBasic.setProductimage(productprofileimage);
int productid = productBasicService.addProduct(productBasic);
ProductBasic productBasic1 = this.productBasicService.getProductById(productid);
for (int index = 0; index < imagesList.size(); index++) {
if (index == 0) {
productBasic1.setProductimage(imagesList.get(0));
}
ProductImage productImage = new ProductImage();
productImage.setProductimage(imagesList.get(index));
this.productImageService.addProductImage(productBasic1, productImage);
}
productBasicService.updateProduct(productBasic1);
imagesList.clear();
productprofileimage =null;
return "redirect:/product/show";
}
ProductDAOImpl :
#Override
#Transactional
public int addProduct(User user, ProductBasic productBasic) {
// I was using getSessionBefore with Eager, it worked, thought of trying openSession
session = this.sessionFactory.openSession();
user.getProductBasics().add(productBasic);
productBasic.setUser1(user);
session.save(productBasic);
System.out.println("Returned product information is"+productBasic.getProductid());
session.flush();
//session.close();
return productBasic.getProductid();
}
#Override
#Transactional
public void updateProduct(User user,ProductBasic productBasic) {
logger.debug("Editing product information");
session = this.sessionFactory.getCurrentSession();
// User user1 = (User) session.get(User.class,id);
user.getProductBasics().add(productBasic);
productBasic.setUser1(user);
session.saveOrUpdate(productBasic);
session.flush();
}
ProductImageDAOImpl :
#Override
#Transactional
public boolean addProductImage(ProductBasic productBasic,ProductImage productImage) {
session = sessionFactory.openSession();
productBasic.getProductImageSet().add(productImage);
productImage.setProductimageupload(productBasic);
productBasic.setImagecount((productBasic.getImagecount()+1));
session.merge(productBasic);
session.saveOrUpdate(productImage);
return true;
}
The controller code shouldn't contain that much service side information, but this is just an attempt to make sure it works..I have defined LazyLoading in model, I can post the code if required, kindly tell me what am I doing wrong. Any pointers are welcome. Thank you for your time.
Extension to my comments
Remove the saveOrUpdate above.
Change the cascade type to ALL
PS: You got exception at UpdateProduct method. but you hve posted code for addProduct.

Resources