i'm trying to configure spring boot in order to have tomcat connection pool to my production database.
My application is NOT web (i have also some difficult to tell that to spring).
I have a Startup class and 3 more classes
the code
#Configuration
#EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
public class Starter {
private static Logger logger;
#Autowired
private static MyController controller;
public static void main(String[] args) {
// SpringApplication.setWebEnvironment(false);
SpringApplication.run(Starter.class, args);
LogbackConfigLoader lcl = new LogbackConfigLoader();
if (lcl.init()) {
logger = LoggerFactory.getLogger(Starter.class);
logger.debug("Initialized....");
}
else{
logger = LoggerFactory.getLogger(Starter.class);
}
logger.info(controller.getProva());
}
}
here is the configuration
`
#Configuration
#ConfigurationProperties(prefix="datasource.NIS")
public class NISDBConfiguration {
private String jdbcInterceptors;
private long validationInterval = 30000;
private org.apache.tomcat.jdbc.pool.DataSource pool;
#Value("${driver-class-name}")
private String driverClassName;
#Value("${url}")
private String url;
#Value("${username}")
private String username;
#Value("${password}")
private String password;
#Value("${maxActive}")
private int maxActive = 30;
#Value("${maxIdle}")
private int maxIdle = 8;
#Value("${minIdle}")
private int minIdle = 8;
#Value("${initialSize}")
private int initialSize = 10;
private String validationQuery;
private boolean testOnBorrow;
private boolean testOnReturn;
private boolean testWhileIdle;
private Integer timeBetweenEvictionRunsMillis;
private Integer minEvictableIdleTimeMillis;
private Integer maxWaitMillis;
public String getJdbcInterceptors() {
return jdbcInterceptors;
}
public void setJdbcInterceptors(String jdbcInterceptors) {
this.jdbcInterceptors = jdbcInterceptors;
}
public long getValidationInterval() {
return validationInterval;
}
public void setValidationInterval(long validationInterval) {
this.validationInterval = validationInterval;
}
public org.apache.tomcat.jdbc.pool.DataSource getPool() {
return pool;
}
public void setPool(org.apache.tomcat.jdbc.pool.DataSource pool) {
this.pool = pool;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public Integer getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(
Integer timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public Integer getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public Integer getMaxWaitMillis() {
return maxWaitMillis;
}
public void setMaxWaitMillis(Integer maxWaitMillis) {
this.maxWaitMillis = maxWaitMillis;
}
#Bean(name = "dsNIS")
public DataSource dataSource() {
this.pool = new org.apache.tomcat.jdbc.pool.DataSource();
this.pool.setDriverClassName(getDriverClassName());
this.pool.setUrl(getUrl());
this.pool.setUsername(getUsername());
this.pool.setPassword(getPassword());
this.pool.setInitialSize(getInitialSize());
this.pool.setMaxActive(getMaxActive());
this.pool.setMaxIdle(getMaxIdle());
this.pool.setMinIdle(getMinIdle());
this.pool.setTestOnBorrow(isTestOnBorrow());
this.pool.setTestOnReturn(isTestOnReturn());
this.pool.setTestWhileIdle(isTestWhileIdle());
if (getTimeBetweenEvictionRunsMillis() != null) {
this.pool
.setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis());
}
if (getMinEvictableIdleTimeMillis() != null) {
this.pool.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis());
}
this.pool.setValidationQuery(getValidationQuery());
this.pool.setValidationInterval(this.validationInterval);
if (getMaxWaitMillis() != null) {
this.pool.setMaxWait(getMaxWaitMillis());
}
if (this.jdbcInterceptors != null) {
this.pool.setJdbcInterceptors(this.jdbcInterceptors);
}
return this.pool;
}
#PreDestroy
public void close() {
if (this.pool != null) {
this.pool.close();
}
}
#Bean(name = "jdbcNIS")
public JdbcTemplate jdbcTemplate(DataSource dsNIS) {
return new JdbcTemplate(dsNIS);
}
}
`
the repository
package org.hp.data;
#Repository
public class NisRepository {
protected final Logger log = LoggerFactory.getLogger(getClass());
#Autowired
#Qualifier("jdbcNIS")
protected JdbcTemplate jdbc;
public String getItem(long id) {
return jdbc.queryForObject("SELECT * FROM sb_item WHERE id=?", itemMapper, id);
}
private static final RowMapper<String> itemMapper = new RowMapper<String>() {
#Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
String item = rs.getString("title");
return item;
}
};
public JdbcTemplate getJdbc() {
return jdbc;
}
public void setJdbc(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
}
the controller
#Controller
public class MyController {
#Autowired
private NisRepository items;
public NisRepository getItems() {
return items;
}
public void setItems(NisRepository items) {
this.items = items;
}
public String getProva(){
return items.getItem(10);
}
}
But i always get exception when running the application of NullPointerException because MyController is not autowired and is always null.
I also try to create a new instance with new (but i believe that this is not correct because of the spring mvc pattern).
What is the problem here?
Thanks in advance
You are using Spring Boot but are trying very hard not to use it. You also state you aren't using a web application but then why do you have a #Controller?
To fix your problem remove the configuration of the DataSource and JdbcTemplate Spring Boot will configure those for you. This basically means remove your NISDBConfiguration class. Just add the correct properties to the application.properties file.
spring.datasource.driver-class-name=<your-driver-here>
spring.datasource.url=<your-url>
spring.datasource.username=<your-username>
spring.datasource.password=<your-password>
And of course the other properties you need, check the reference guide for more properties.
Remove the #Qualifier from the JdbcTemplate property in your repository and you also don't need the getter and setter. I would suggest using constructor based injection.
package org.hp.data;
#Repository
public class NisRepository {
protected final Logger log = LoggerFactory.getLogger(getClass());
protected final JdbcTemplate jdbc;
#Autowired
public NisRepository(JdbcTemplate jbc) {
this.jdbc=jdbc;
}
public String getItem(long id) {
return jdbc.queryForObject("SELECT * FROM sb_item WHERE id=?", itemMapper, id);
}
private static final RowMapper<String> itemMapper = new RowMapper<String>() {
#Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
String item = rs.getString("title");
return item;
}
};
}
If you don't have a web application replace #Controller with #Service.
Then rewrite your starter class.
#SpringBootApplication
public class Starter {
private static Logger logger;
public static void main(String[] args) {
// SpringApplication.setWebEnvironment(false);
ApplicationContext ctx = SpringApplication.run(Starter.class, args);
LogbackConfigLoader lcl = new LogbackConfigLoader();
if (lcl.init()) {
logger = LoggerFactory.getLogger(Starter.class);
logger.debug("Initialized....");
}
else{
logger = LoggerFactory.getLogger(Starter.class);
}
MyController controller = ctx.getBean(MyController.class);
logger.info(controller.getProva());
}
}
Looks like you are also trying to circument spring boots config loading here? Try to work with the framework not against it.
If you don't have a web application don't include the spring-boot-starter-web in your dependencies and also make sure you don't have any other web related things in there. Spring Boot auto detects the web environment and tries to bootstrap classes for that, if those aren't there it will just run as a plain java application.
Related
i try to authwire configuration using spring
All complies fine and the server is running , but the configurator never triggered
//Main class :
#SpringBootApplication
public class MainApplication {
public static void main(String[] args)
{
SpringApplication app = new SpringApplication(MainApplication.class);
app.setDefaultProperties(Collections
.singletonMap("server.port", "8083"));
app.run(args);
}
}
// this class i like the Map<String, CarsInfo> carsInfos map will be filled automatically
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class AppManager {
private final Map<String, CarsInfo> carsInfos;
#Autowired
public AppManager(Map<String, CarsInfo> carsInfos) {
this.carsInfos = carsInfos;
}
}
public class CarsInfo {
private String id;
private String data;
public CarsInfo(String id,String data) {
this.id = id;
this.data = data;
}
}
#Configuration
public class Config1 {
#Bean ("DATA_FILLER")
public String getData() {
return "Car Test";
}
#Bean(IDs.CAR_ID)
public CarsInfo carInfo(#Qualifier("DATA_FILLER") String data) {
return new CarsInfo(IDs.CAR_ID,data);
}
}
#Configuration
public class Config2 {
#Bean("DATA_FILLER")
public String getData() {
return "Tractor Test";
}
#Bean(IDs.TRACTOR_ID)
public CarsInfo tractorInfo(#Qualifier("DATA_FILLER") String data) {
return new CarsInfo(IDs.CAR_ID,data);
}
}
public class IDs {
public static final String CAR_ID = "car_id";
public static final String TRACTOR_ID = "tractor_id";
}
I am Trying to write test case for a method which takes URI as input and maps with modelmapper.
however, I am getting null pointer exception for this.
I have added every possible implementaion of class which I want to test.
if you guy's need more for compilation tell me in comment section.
this one is actual implementation which I want to mock
#Override
public ApplicationScanConfigDTO getApplicationScanConfig(int account_id, String appAppScanConfigId) {
URI getUri = UriComponentsBuilder.fromPath("/").pathSegment("api/scheduleOnDemand")
.queryParam("Account_Id", account_id).queryParam("applicationConfigScanId", appAppScanConfigId).build()
.toUri();
return modelMapper.map(apiClient.getOperation(getUri, Object.class), ApplicationScanConfigDTO.class);
}
This is what I was trying
#Test
void testGetApplicationScanConfig() throws Exception {
URI getUri = new URI("/api/scheduleOnDemand?Account_Id=1&applicationConfigScanId=1");
modelmapper.map(restTemplate.getForEntity(getUri, JSONObject.class), ApplicationScanConfigDTO.class);
}
apiclient implementation
#Override
public <R> R getOperation(URI uri, Class<R> rClasss) {
URI builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
.path(uri.getPath())
.query(uri.getQuery())
.build()
.toUri();
return restTemplate.getForObject(builder, rClasss);
}
ApplicationConfigDTO actual implementation:
public class ApplicationScanConfigDTO {
private Integer id;
private String serverName;
private Integer accountId;
private String ipAddress;
private String subnetRange;
private Integer credentialId;
private String credentialName;
private String os;
private List<String> ibmLibrary;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getServerName() {
return serverName;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public Integer getAccountId() {
return accountId;
}
public void setAccountId(Integer accountId) {
this.accountId = accountId;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getSubnetRange() {
return subnetRange;
}
public void setSubnetRange(String subnetRange) {
this.subnetRange = subnetRange;
}
public Integer getCredentialId() {
return credentialId;
}
public void setCredentialId(Integer credentialId) {
this.credentialId = credentialId;
}
public String getCredentialName() {
return credentialName;
}
public void setCredentialName(String credentialName) {
this.credentialName = credentialName;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public List<String> getIbmLibrary() {
return ibmLibrary;
}
public void setIbmLibrary(List<String> ibmLibrary) {
this.ibmLibrary = ibmLibrary;
}
}
I created a chat on spring boot. Where several people can correspond. So I created a database and there I store all messages from users. So I want, if a new user enters the chat, then he should see only the last 10 messages. The problem is that the program does not take the last 10 messages from the database, it takes them from the server, this is not correct. I want him to take the last 10 messages from the database.
My code
Rest Controller
#SpringComponent
#org.springframework.web.bind.annotation.RestController
public class RestController {
private List<Message> store;
public RestController() {
store = new ArrayList<>();
}
#PutMapping("/api/save")
public void saveMessage(#RequestBody String chatMessage) {
store.add(new Gson().fromJson(chatMessage, Message.class));
if (store.size() > 10)
store.remove(0);
}
#GetMapping("/api/last")
public String getLasts() {
return new Gson().toJson(store);
}
}
Message class
#Entity
#Table(name = "chatMessages")
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String fromV;
private String messageV;
private Timestamp time;
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public Message() { }
public String getFromV() {
return fromV;
}
public void setFromV(String fromV) {
this.fromV = fromV;
}
public String getMessageV() {
return messageV;
}
public void setMessageV(String messageV) {
this.messageV = messageV;
}
public Message(String from, String message) {
this.fromV = from;
this.messageV = message;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFrom() {
return fromV;
}
public void setFrom(String from) {
this.fromV = from;
}
public String getMessage() {
return messageV;
}
public void setMessage(String message) {
this.messageV = message;
}
}
MessageRepository
#Repository
public interface MessageRepository extends JpaRepository<Message, Long> {
}
MessageService
public interface MessageService {
void add(Message message);
List<Message> getAllMessages();
}
MessageServiceImpl
#Service
#Transactional
public class MessageServiceImpl implements MessageService {
private final MessageRepository repository;
#Autowired
public MessageServiceImpl(MessageRepository repository) {
this.repository = repository;
}
#Override
public void add(Message message) {
message.setTime(new Timestamp(new Date().getTime()));
repository.saveAndFlush(message);
}
#Override
public List<Message> getAllMessages() {
return repository.findAll();
}
}
MessageList
public MessageList() {
addClassName("message-list");
}
#Override
public void add(Component... components) {
super.add(components);
components[components.length-1]
.getElement()
.callFunction("scrollIntoView");
}
}
Application Controller
server.port=8080
# This is a workaround for https://github.com/vaadin/spring/issues/381
spring.servlet.multipart.enabled = false
spring.datasource.url=jdbc:mysql://localhost:3306/chat?createDatabaseIfNotExist=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
To be frankly,i don't understand the purpose of the object store in your controller. If you want to query the last 10 messages.You can just implement a method in repository and invoke it in your controller.
MessageRepository
#Repository
public interface MessageRepository extends JpaRepository<Message, Long> {
List<Message> findTop10ByOrderByTimeDesc();
}
Hi This is my Row Mapper class.
public class UserRowMapper implements RowMapper<UserData> {
#Override
public UserData mapRow(ResultSet resultSet, int line) throws SQLException {
UserData userData = new UserData();
try
{
userData.setUserID(resultSet.getString("User_ID"));
userData.setUserName(resultSet.getString("User_Name"));
userData.setUserPassword(resultSet.getString("User_Password"));
userData.setUserRole(resultSet.getString("User_Role"));
userData.setUserStatus(resultSet.getString("User_Status"));
userData.setUserLogStatus(resultSet.getString("UserLog_Status"));
userData.setUserAccountName(resultSet.getString("User_AccountName"));
userData.setUserAccountID(resultSet.getString("User_AccountID"));
userData.setUserEmailID(resultSet.getString("User_EmailID"));
userData.setUserPasswordStatus(resultSet.getString("User_Password_ExpiryStatus"));
userData.setUserIDStatus(resultSet.getString("User_ID_Status"));
userData.setAcatTenantID(resultSet.getLong("acatTenant_ID"));
userData.setUserRoleCode(resultSet.getLong("User_Role_Code"));
userData.setUserSkillSetCode(resultSet.getLong("User_SkillSet_Code"));
userData.setUserAccountCode(resultSet.getLong("User_Account_Code"));
return userData;
}
catch (EmptyResultDataAccessException e)
{
return null;
}
}
}
and this is my Model class.
public class UserData {
private String userID;
private String userPassword;
private String userRole;
private String userStatus;
private String userLogStatus;
private String userName;
private String userAccountName;
private String userAccountID;
private String userIDStatus;
private String userPasswordStatus;
private String userEmailID;
private String userAdminID;
private String deactivationComment;
private String reqPageID;
private String userSessionID;
private String reqFunctionalityID;
private long userAccountCode;
private long userRoleCode;
private long userSkillSetCode;
private long acatTenantID;
public long getUserAccountCode() {
return userAccountCode;
}
public void setUserAccountCode(long userAccountCode) {
this.userAccountCode = userAccountCode;
}
public long getUserRoleCode() {
return userRoleCode;
}
public void setUserRoleCode(long userRoleCode) {
this.userRoleCode = userRoleCode;
}
public long getUserSkillSetCode() {
return userSkillSetCode;
}
public void setUserSkillSetCode(long userSkillSetCode) {
this.userSkillSetCode = userSkillSetCode;
}
public long getAcatTenantID() {
return acatTenantID;
}
public void setAcatTenantID(long acatTenantID) {
this.acatTenantID = acatTenantID;
}
public String getReqFunctionalityID() {
return reqFunctionalityID;
}
public void setReqFunctionalityID(String reqFunctionalityID) {
this.reqFunctionalityID = reqFunctionalityID;
}
public String getReqPageID() {
return reqPageID;
}
public void setReqPageID(String reqPageID) {
this.reqPageID = reqPageID;
}
public String getUserSessionID() {
return userSessionID;
}
public void setUserSessionID(String userSessionID) {
this.userSessionID = userSessionID;
}
public String getUserAdminID() {
return userAdminID;
}
public void setUserAdminID(String userAdminID) {
this.userAdminID = userAdminID;
}
public String getDeactivationComment() {
return deactivationComment;
}
public void setDeactivationComment(String deactivationComment) {
this.deactivationComment = deactivationComment;
}
public String getUserIDStatus() {
return userIDStatus;
}
public void setUserIDStatus(String userIDStatus) {
this.userIDStatus = userIDStatus;
}
public String getUserPasswordStatus() {
return userPasswordStatus;
}
public void setUserPasswordStatus(String userPasswordStatus) {
this.userPasswordStatus = userPasswordStatus;
}
public String getUserEmailID() {
return userEmailID;
}
public void setUserEmailID(String userEmailID) {
this.userEmailID = userEmailID;
}
public String getUserAccountID() {
return userAccountID;
}
public void setUserAccountID(String userAccountID) {
this.userAccountID = userAccountID;
}
public String getUserAccountName() {
return userAccountName;
}
public void setUserAccountName(String userAccountName) {
this.userAccountName = userAccountName;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
public String getUserStatus() {
return userStatus;
}
public void setUserStatus(String userStatus) {
this.userStatus = userStatus;
}
public String getUserLogStatus() {
return userLogStatus;
}
public void setUserLogStatus(String userLogStatus) {
this.userLogStatus = userLogStatus;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
The above classes are my Row Mapper and Model class.i do not know how to write junit test class for Row Mapper class .please any one guide me how to write junit test for these classes.
Hi here is my Junit test code for above classes.
public class UserRowMapperTest {
UserRowMapper userRowMapper=null;
#Before
public void runBeforeEachTest(){
userRowMapper= new UserRowMapper();
}
#After
public void runAfterEachTest(){
userRowMapper=null;
}
#Test
public void testMapRow(){
userRowMapper.mapRow(resultSet, line);
}
}
From my point of view there is nothing to test here.
You should create unit tests only for the methods which have some business logic. I don't see the reason to test the methods which are using just getters and setters because in general they don't do anything.
However, if you want just to practice this is the advice what you could do for the unit test. First of all check some questions on how to write the unit tests because it feels like you don't understand what you need/want to achieve.
In general this is the sketch of what you want:
#Test
public void testMapRow(){
// SETUP SUT
UserRowMapper userRowMapper = new UserRowMapper()
// fill (prepare) in the Object that you want to pass to a method.
ResultSet resultSet = createResultSet();
// EXERCISE
UserData resultData = userRowMapper.mapRow(resultSet, line);
// VERIFY
Assert.assertEquals(expectedValue, resultData.getSomeValue())
}
p.s. By the way, there is no point in line parameter in this method because you don't use it.
And about the NullPointerException, please, have a look to quite popular question about it.
I'm working on a project and this is first time that I'm using hibernate tech.
I made my hibernate configuration file as
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">diobookbla</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mobil</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.default_schema">mobil</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
</session-factory>
</hibernate-configuration>
And this I've done my reverse engineering configuration so I get my MySQL tables as Java classes.
This is my User Class;
package Tables;
// default package
// Generated Nov 24, 2012 1:08:44 AM by Hibernate Tools 3.4.0.CR1
import java.util.HashSet;
import java.util.Set;
/**
* Users generated by hbm2java
*/
public class Users implements java.io.Serializable {
private Integer userId;
private Integer userFbId;
private String userFbToken;
private String userName;
private String userLastName;
private String userEmail;
private String userAdress;
private String userFavouritedTopicsCount;
private String userCreatedTopicsCount;
private String userRecommendedTopicsCount;
private Integer userFollowingsCount;
private Integer userFollowersCount;
private String userBio;
private String userProfilePicUrl;
private Boolean userIsOnline;
private Integer userPoint;
private Set topicses = new HashSet(0);
private Set mentionsForMentionedId = new HashSet(0);
private Set favouritetopicses = new HashSet(0);
private Set mentionsForMentionerId = new HashSet(0);
private Set postlikes = new HashSet(0);
private Set userfollowsForFollowingId = new HashSet(0);
private Set topicrecommends = new HashSet(0);
private Set userfollowsForFollowerId = new HashSet(0);
public Users() {
}
public Users(Integer userFbId, String userFbToken, String userName,
String userLastName, String userEmail, String userAdress,
String userFavouritedTopicsCount, String userCreatedTopicsCount,
String userRecommendedTopicsCount, Integer userFollowingsCount,
Integer userFollowersCount, String userBio,
String userProfilePicUrl, Boolean userIsOnline, Integer userPoint,
Set topicses, Set mentionsForMentionedId, Set favouritetopicses,
Set mentionsForMentionerId, Set postlikes,
Set userfollowsForFollowingId, Set topicrecommends,
Set userfollowsForFollowerId) {
this.userFbId = userFbId;
this.userFbToken = userFbToken;
this.userName = userName;
this.userLastName = userLastName;
this.userEmail = userEmail;
this.userAdress = userAdress;
this.userFavouritedTopicsCount = userFavouritedTopicsCount;
this.userCreatedTopicsCount = userCreatedTopicsCount;
this.userRecommendedTopicsCount = userRecommendedTopicsCount;
this.userFollowingsCount = userFollowingsCount;
this.userFollowersCount = userFollowersCount;
this.userBio = userBio;
this.userProfilePicUrl = userProfilePicUrl;
this.userIsOnline = userIsOnline;
this.userPoint = userPoint;
this.topicses = topicses;
this.mentionsForMentionedId = mentionsForMentionedId;
this.favouritetopicses = favouritetopicses;
this.mentionsForMentionerId = mentionsForMentionerId;
this.postlikes = postlikes;
this.userfollowsForFollowingId = userfollowsForFollowingId;
this.topicrecommends = topicrecommends;
this.userfollowsForFollowerId = userfollowsForFollowerId;
}
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getUserFbId() {
return this.userFbId;
}
public void setUserFbId(Integer userFbId) {
this.userFbId = userFbId;
}
public String getUserFbToken() {
return this.userFbToken;
}
public void setUserFbToken(String userFbToken) {
this.userFbToken = userFbToken;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserLastName() {
return this.userLastName;
}
public void setUserLastName(String userLastName) {
this.userLastName = userLastName;
}
public String getUserEmail() {
return this.userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserAdress() {
return this.userAdress;
}
public void setUserAdress(String userAdress) {
this.userAdress = userAdress;
}
public String getUserFavouritedTopicsCount() {
return this.userFavouritedTopicsCount;
}
public void setUserFavouritedTopicsCount(String userFavouritedTopicsCount) {
this.userFavouritedTopicsCount = userFavouritedTopicsCount;
}
public String getUserCreatedTopicsCount() {
return this.userCreatedTopicsCount;
}
public void setUserCreatedTopicsCount(String userCreatedTopicsCount) {
this.userCreatedTopicsCount = userCreatedTopicsCount;
}
public String getUserRecommendedTopicsCount() {
return this.userRecommendedTopicsCount;
}
public void setUserRecommendedTopicsCount(String userRecommendedTopicsCount) {
this.userRecommendedTopicsCount = userRecommendedTopicsCount;
}
public Integer getUserFollowingsCount() {
return this.userFollowingsCount;
}
public void setUserFollowingsCount(Integer userFollowingsCount) {
this.userFollowingsCount = userFollowingsCount;
}
public Integer getUserFollowersCount() {
return this.userFollowersCount;
}
public void setUserFollowersCount(Integer userFollowersCount) {
this.userFollowersCount = userFollowersCount;
}
public String getUserBio() {
return this.userBio;
}
public void setUserBio(String userBio) {
this.userBio = userBio;
}
public String getUserProfilePicUrl() {
return this.userProfilePicUrl;
}
public void setUserProfilePicUrl(String userProfilePicUrl) {
this.userProfilePicUrl = userProfilePicUrl;
}
public Boolean getUserIsOnline() {
return this.userIsOnline;
}
public void setUserIsOnline(Boolean userIsOnline) {
this.userIsOnline = userIsOnline;
}
public Integer getUserPoint() {
return this.userPoint;
}
public void setUserPoint(Integer userPoint) {
this.userPoint = userPoint;
}
public Set getTopicses() {
return this.topicses;
}
public void setTopicses(Set topicses) {
this.topicses = topicses;
}
public Set getMentionsForMentionedId() {
return this.mentionsForMentionedId;
}
public void setMentionsForMentionedId(Set mentionsForMentionedId) {
this.mentionsForMentionedId = mentionsForMentionedId;
}
public Set getFavouritetopicses() {
return this.favouritetopicses;
}
public void setFavouritetopicses(Set favouritetopicses) {
this.favouritetopicses = favouritetopicses;
}
public Set getMentionsForMentionerId() {
return this.mentionsForMentionerId;
}
public void setMentionsForMentionerId(Set mentionsForMentionerId) {
this.mentionsForMentionerId = mentionsForMentionerId;
}
public Set getPostlikes() {
return this.postlikes;
}
public void setPostlikes(Set postlikes) {
this.postlikes = postlikes;
}
public Set getUserfollowsForFollowingId() {
return this.userfollowsForFollowingId;
}
public void setUserfollowsForFollowingId(Set userfollowsForFollowingId) {
this.userfollowsForFollowingId = userfollowsForFollowingId;
}
public Set getTopicrecommends() {
return this.topicrecommends;
}
public void setTopicrecommends(Set topicrecommends) {
this.topicrecommends = topicrecommends;
}
public Set getUserfollowsForFollowerId() {
return this.userfollowsForFollowerId;
}
public void setUserfollowsForFollowerId(Set userfollowsForFollowerId) {
this.userfollowsForFollowerId = userfollowsForFollowerId;
}
}
This are my classes that uses the my Users class
public boolean SaveDatabase(Object object) {
try {
SessionFactory sessionfactory = new Configuration().configure()
.buildSessionFactory();
session = sessionfactory.openSession();
try {
session.save(object);
session.flush();
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
} finally {
session.close();
}
return true;
}
and
public boolean RegisterUsers(Users user) {
if (SaveDatabase(user)) {
return true;
} else {
return false;
}
}
At least this is my test class.
import Tables.Users;
import DAO.LogIn;
public class Test {
public static void main(String[] args) {
//Test RegisterUser and GetUsersWithId in here
LogIn test = new LogIn();
Users user = new Users();
user.setUserEmail("email");
user.setUserAdress("adres here");
user.setUserFbId(3);
test.RegisterUsers(user);
}
}
When I execute my test class I got this error;
Unknown entity: Tables.Users .
I've done some researches about this and it I got up with that I must create persistence.xml file or use spring tech.
Sorry for long post, I'm waiting for any helps.
Thanks.
you need to let Hibernate know that which class would be mapped to persistent layer(database table for example). You could either do that with annotation or using hbm.xml approach.
In your User class, I didn't see any hibernate annotation. I therefore guess you wanna do it with hbm.xml.
You need add something like
<mapping resource="path/to/your/User.hbm.xml"/>
to your hibernate.cfg.xml.
And of course you have to create the User.hbm.xml as well. do some research on that, how to do hibernate mappings.
Personally I suggest that you do hibernate mapping with annotations. There are tons of resources about that on net.
Good luck!