Spring boot MongoDB configuration - mysql

I'm working in a spring boot application & use both MySQL & mongodb as databases.Below you can see spring boot main application for MySQL.
#EnableFeignClients(basePackages = {"com.saman.kamal.nimalservice"})
#EnableDiscoveryClient
#SpringBootApplication(scanBasePackages = {"com.saman.kamal.nimalservice"})
#EnableOAuth2Client
#EnableJpaRepositories(basePackages = {"com.saman.kamal.nimalservice.repository"})
#EntityScan(basePackages = {"com.saman.kamal.nimalservice.domain"})
public class HuththaApplication {
public static void main(String[] args) {
SpringApplication.run(HuththaApplication.class, args);
}
}
if I use mongodb instead of mysql
#EntityScan(basePackages = {"com.saman.kamal.nimalservice.domain"})
should be change. How should be change?
Below you can see my entity class.
import java.io.Serializable;
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#ToString
#Document
public class EbankLog implements Serializable {
private static final Long serialVersionUID = 1L;
#Id
private String bothala;
private String sapaththu;
private String sereppu;
private String kanda;
private String bag;
}

You have not let Spring know where your MongoDb repositories are. In order to do that use #EnableMongoRepositories. See below codes:
#EnableMongoRepositories(basePackages = "your.mongodb.repositories.package")
#EnableFeignClients(basePackages = {"com.saman.kamal.nimalservice"})
#EnableDiscoveryClient
#SpringBootApplication(scanBasePackages = {"com.saman.kamal.nimalservice"})
#EnableOAuth2Client
#EnableJpaRepositories(basePackages = {"com.saman.kamal.nimalservice.repository"})
#EntityScan(basePackages = {"com.saman.kamal.nimalservice.domain"})
public class HuththaApplication {
public static void main(String[] args) {
SpringApplication.run(HuththaApplication.class, args);
}
}

Related

How to save a raw JSON in the MySQL using JPA

I need to save this JSON in MySQL database, and later recover it and display in the frontend
I'm using Spring boot with JPA, but i have been facing errors about serialization when the Request comes from frontend, like this:
I send the json from the frontend to my controller:
#RestController
#RequestMapping("/theoriclesson")
#CrossOrigin
public class TheoricLessonController implements ITheoricLessonController {
#Autowired
private TheoricLessonRepository theoricLessonRepository;
#Autowired
private ModuleRepository moduleRepository;
#Override
#PostMapping("/")
public void add(#RequestBody TheoricLesson theoricLesson) {
Module module = new Module();
module.setName("Modulo de teste");
TheoricLesson tc = new TheoricLesson();
Module mP = moduleRepository.save(module);
tc.setModule(mP);
theoricLessonRepository.save(tc);
}
}
and my entities:
#Data
#Entity
#Builder
public class TheoricLesson {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long xpEarned;
private String lessonName;
#Embedded
private DraftJsText draftJsText;
#ManyToOne
#JoinColumn(name = "module_id")
#JsonIgnore
private Module module;
}
#Getter
#Setter
#ToString
#Embeddable
public class DraftJsText {
public DraftJsText() {
}
public DraftJsText(String blocks, String entityMap) {
this.blocks = blocks;
this.entityMap = entityMap;
}
#Column(columnDefinition = "JSON")
private String blocks;
#Column(columnDefinition = "JSON")
private String entityMap;
}

can't see the contents of DB in HTML

I connected my bat to the database.
I mapped it to view the contents in HTML,
but typing url(/index) in the address bar, I can only see the contents of the table.
What is the problem?
public class Controller {
#Autowired
noticeService ns;
#RequestMapping(value="/index", method = RequestMethod.GET)
public ModelAndView index (HttpServletRequest request) {
ModelAndView mav = new ModelAndView();
List<noticeModel>noticeList = ns.getNotice();
mav.addObject("noticeList", noticeList);
mav.setViewName("index"); // HTML ADDRESS
return mav;
}
}
#Builder #Data
public class noticeModel {
private int notice_id;
private String notice_tilte;
private String notice_name;
private Date notice_created_date;
private Date notice_revised_date;
private String notice_text;
private String notice_pw;
}
#Service
public class noticeService {
#Autowired
public noticeMapper mapper;
public List<noticeModel> getNotice() {
return mapper.getNotice();
}
}
#Repository
#Mapper
public interface noticeMapper {
List<noticeModel> getNotice();
}

How to correct sql statement to give correct result

I'm running a local MySQL Server on port 3306 with a schema "sys" featuring a table "users"
Now I have a small spring boot application to query all entries from that table.
Model for that table is:
package com.example.databaseneu.model;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Users {
#Id
// #Column(name = "id")
private int id;
// #Column(name = "name")
private String name;
// #Column(name = "salary")
private int salary;
// #Column(name = "team_name")
private String team_name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getTeam_name() {
return team_name;
}
public void setTeam_name(String team_name) {
this.team_name = team_name;
}}
The connection works, but the query doesnt seem to deliver the right result as I get the Whitelabel Error Page.
Query to get all elements from the table (autogenerated by repository)
Hibernate:
select
users0_.id as id1_0_,
users0_.name as name2_0_,
users0_.salary as salary3_0_,
users0_.team_name as team_nam4_0_
from
users users0_
So I'm uncertain if i defined the Entity wrong or something else alltogether
#Column Tag doesnt do the trick.
---Edit---
package com.example.databaseneu.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.databaseneu.model.Users;
import com.example.databaseneu.repository.UserRepository;
#Controller // This means that this class is a Controller
#RequestMapping(path = "/demo") // This means URL's start with /demo (after Application path)
public class MainController {
#Autowired
private UserRepository userRepository;
#GetMapping(path = "/add")
public #ResponseBody String addNewUser(#RequestParam String name, #RequestParam int salary,
#RequestParam String team_name) {
Users n = new Users();
n.setName(name);
n.setSalary(salary);
n.setTeam_name(team_name);
userRepository.save(n);
return "Saved";
}
#GetMapping(path = "/all")
public Iterable<Users> getAllUsers() {
return userRepository.findAll();
}}
So id navigate to localhost:8080/demo/all
You have written all correct expect for one thing. Mark your return-type with #ResponseBody annotation -- similar to your addNewUser method.
#GetMapping(path = "/all")
public #ResponseBody Iterable<Users> getAllUsers() {
return userRepository.findAll();
}}
Hopefully this should work. If you still face issues, post it here.

Using Multiple Database in Spring boot

I encounted a problem when I wanted to work between two database, I wanted to use the table 1 in database 1 and the table 2 in database 2, I tried so many ways, but all seems not work.
spring.datasource.primary.url = jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8
spring.datasource.primary.username = root
spring.datasource.primary.password = xxxx
spring.datasource.primary.driverClassName=com.mysql.jdbc.Driver
spring.datasource.secondary.url = jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=UTF-8
spring.datasource.secondary.username = root
spring.datasource.secondary.password = xxxx
spring.datasource.secondary.driverClassName=com.mysql.jdbc.Driver
above is my application.properties. Then I used #Primary setting spring.datasource.primary as the primary database in config file.
#Entity
#Table(name = "User")
public class User {
#Id
#NotNull
#Column(name = "phoneid")
private String phoneid;
}
public interface UserDAO extends CrudRepository<User, String> {
public User findByPhoneid(String phoneid);
}
I want to connect to database spring.datasource.primary and use the table User in it.
#Entity
#Table(name = "Favorite_Restaurant")
public class FavoriteRestaurant {
#Id
#NotNull
#Column(name = "favorite_restaurantid")
private int favoriteRestaurantId;
}
public interface FavoriteRestaurantDAO extends JpaRepository<FavoriteRestaurant, Integer> {
public List<FavoriteRestaurant> findAll(Sort sort);
}
I want to connect to database spring.datasource.secondary and use the table FavoriteRestaurant in it.
However when I Autowired UserDAo and FavoriteRestaurantDAO in My Service, It seems just like it autowired both userdao and favoriterestaurantdao from primary database. How can I inject FavoriteRestaurantDAO from secondary database!!!!! help!!!!!!
To be able to use several datasources you need to have several persistent unit configurations.
I will assume that you've got datasourceA and datasourceB to configure.
We have one configuration class for each of our persistent units. The listing contains the class for datasourceA (you will have to copy and adjust the configuration for datasourceB).
It's also a good idea not to mix the entities from different persistent units.
So we have separated them based on the package. We have created an empty class
SpringRootPackageMarker so that it tells spring which packages to scan.
Note! the SpringRootPackageMarker class is used in both #EnableJpaRepositories and in getDatasourceAEntityManagerFactoryBean method
So this is our way how to do it:
#DependsOn("transactionManager")
#EnableJpaRepositories(
basePackageClasses = SpringRootPackageMarker.class,
entityManagerFactoryRef = "datasourceAEntityManager",
transactionManagerRef = "transactionManager")
public class DatasourceAPersistenceUnitConfiguration {
private static final String DATASOURCE_A_PERSISTENT_UNIT_NAME = "datasourceAPU";
#DependsOn("transactionManager") // for unit tests
#Bean(name = "datasourceAEntityManager")
public LocalContainerEntityManagerFactoryBean getDatasourceAEntityManagerFactoryBean() {
final LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setPersistenceUnitName(DATASOURCE_A_PERSISTENT_UNIT_NAME);
factory.setDataSource(getDatasourceA());
factory.setJpaVendorAdapter(getDatasourceAJpaVendorAdapter());
factory.setPackagesToScan(SpringRootPackageMarker.class.getPackage().getName());
Properties jpaProperties = getDatasourceAJpaProperties();
factory.setJpaProperties(jpaProperties);
return factory;
}
#Bean
public DataSource getDatasourceA() {
DataSource datasource = null;
// prepare datasource A;
return datasource;
}
private JpaVendorAdapter getDatasourceAJpaVendorAdapter() {
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
//custom configuration for datasource A
return vendorAdapter;
}
private Properties getDatasourceAJpaProperties() {
Properties jpaProperties = new Properties();
//custom properties
return jpaProperties;
}
}
}
if you plan to inject the entityManager into your application you'll have to do it this way:
#PersistenceContext(unitName= DatasourceAPersistenceUnitConfiguration.DATASOURCE_A_PERSISTENT_UNIT_NAME)
private EntityManager manager;
Finally, I solved this problem by adding #EnableAutoConfiguration above my config class
#Configuration
#EnableJpaRepositories(basePackages = "datamodel.dao", entityManagerFactoryRef = "localEntityManagerFactory", transactionManagerRef = "localTransactionManager")
#EnableTransactionManagement
#EnableAutoConfiguration ///the key to make spring boot know your config!!!!!!!!!!!!!
public class MainDataConfig {
#Bean
#ConfigurationProperties(prefix = "datasource.main")
#Primary
public DataSource localDataSource() {
return DataSourceBuilder.create().build();
}
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean localEntityManagerFactory(final EntityManagerFactoryBuilder builder) {
return builder.dataSource(localDataSource()).packages("datamodel.domain")
.persistenceUnit("mainPersistenceUnit").build();
}
#Bean
#Primary
public JpaTransactionManager localTransactionManager(#Qualifier("localEntityManagerFactory") final EntityManagerFactory factory) {
return new JpaTransactionManager(factory);
}
}

how to handle Json body in post request in jax-rs

I have a project (homework) about JAX-RS. I'm working with NetBeans, Jersey and Tomcat.
This is my "User" class for main object in the system.
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="user")
public class User {
//#XmlElement
//public int id ;
#XmlElement
public String username;
#XmlElement
public String fullname;
#XmlElement
public String gender;
#XmlElement
public String birthDate;
public User(){
}
public User(String username,String fullname, String gender,String birthDate){
//this.id = id;
this.username = username;
this.fullname = fullname;
this.gender = gender;
this.birthDate = birthDate;
}
}
This is my "JAXBContextResolver" Class
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
#Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext>{
private JAXBContext context;
private Class[] types = {User.class};
public JAXBContextResolver() throws Exception {
this.context =
new JSONJAXBContext( JSONConfiguration.mapped().build(), types);
}
#Override
public JAXBContext getContext(Class<?> objectType) {
for (Class type : types) {
if (type == objectType) {
return context;
}
}
return null;
}
}
And this is my post method in the "UserService" class
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public List<User> createNewUser(User tUser) {
List<User> list = new ArrayList<User>();
list.add(tUser);
return list;
}
When I am trying a post new user in the localhost with RESTClient (Firefox add-ons) my request body is a json input like that:
{"user":{"username":"blabla","fullname":"blabla","gender":"M","birthDate":"05.01.1978"}}
In the post method (in the UserService class) must the variable "tUser" automatically filled with the coming input ? "tUser" variable shows null elements in it in the debugging mode like that:
If I know wrong could somebody correct me please? Why this values shows null? Must not them shows "blabla" - "blabla" - "M" - "05.01.1878" ? Could you help me please?
I solved this problem; In the JAXBContextResolver class I change the method like that :
public JAXBContextResolver() throws Exception {
this.context =
new JSONJAXBContext( JSONConfiguration.mapped().rootUnwrapping(false).build(), types);
}
The difference with the first one is adding "rootUnwrapping(false)" expression.
#XmlRootElement is not working in your example. Send
{"username":"blabla","fullname":"blabla","gender":"M","birthDate":"05.01.1978"}
instead
EDIT
1)
public List<User> createNewUser(Request tUser)
and class
class Request
{
public User user;
}
2)
public List<User> createNewUser(String tUser)
and convert String to object using google-gson or jackson json processor