I am trying to see my table created through java in H2 console, but i cannot see any table created in H2 console. I am using spring boot, and i am not using spring security, just i have created a simple dummy code to try H2 database for understanding. I have tried many solutions provided on questions asked on the same topic on stack-overflow but non of them works for me.
My Config property file is:
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:file:D:/temp/test
Entity class code are as follows:
#Entity
public class Alien {
#Id
private int aId;
private String aName;
public int getaId() {
return aId;
}
public void setaId(int aId) {
this.aId = aId;
}
public String getaName() {
return aName;
}
public void setaName(String aName) {
this.aName = aName;
}
}
When you log in to your H2 console in the browser you have to specify the JDBC URL to your database as you don't use the default in-memory one.
Your JDBC URL is jdbc:h2:file:D:/temp/test. Once you specify this URL in the H2 console login screen, put in the correct username and password, you should be able to see your file-based local database.
Use #Table for creatting a table from entity class
#Entity
#Table(name="alien")
public class Alien {
#Id
private int aId;
private String aName;
public int getaId() {
return aId;
}
public void setaId(int aId) {
this.aId = aId;
}
public String getaName() {
return aName;
}
public void setaName(String aName) {
this.aName = aName;
}
}
Related
I am trying to create a Spring Boot CRUD application using Cassandra. I created a docker image and I already configured Cassandra, in CassandraConfiguration class but still is not creating my tables.
My CassandraConfiguration.java code:
#Configuration
#EnableCassandraRepositories
public class CassandraConfiguration extends AbstractCassandraConfiguration {
#Value("${env.values.cassandra.keyspace.name}")
private String keyspaceName;
.......................................
#Override
protected String getKeyspaceName() {
return keyspaceName;
}
#Override
protected int getPort() {
return contactPort;
}
#Override
protected String getContactPoints() {
return contactPoint;
}
#Override
public SchemaAction getSchemaAction() {
return SchemaAction.CREATE_IF_NOT_EXISTS;
}
#Override
protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
return List.of(
CreateKeyspaceSpecification.createKeyspace(keyspaceName)
.ifNotExists()
.withSimpleReplication(3));
}
#Bean
#Override
public CqlSessionFactoryBean cassandraSession() {
CqlSessionFactoryBean cassandraSession =
super.cassandraSession(); // super session should be called only once
cassandraSession.setUsername(username);
cassandraSession.setPassword(password);
return cassandraSession;
}
}
My entity:
#Table
#AllArgsConstructor
#NoArgsConstructor
#Builder
#EqualsAndHashCode(of = {"id"})
#Getter
#Setter
public class Account {
#PrimaryKey private String id = UUID.randomUUID().toString();
private String username;
private String email;
private String name;
private String password;
}
My pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
After I've done quick check of the code and configuration you posted, nothing was obvious to me as being incorrect.
My suggestion is to review the application logs looking specifically for errors and warnings from the Cassandra Java driver. Chances are the Cassandra cluster is unreachable from your application usually because of some networking issue.
You will need to verify that there is network connectivity between your application and the contact points + CQL port you've configured. Cheers!
Well, I'm using Hibernate for the first time and, unexpectedly, it works. Except for one thing: an insert with a pk already inserted overwrite the record instaed of preventing it.
That's my simple code:
#Controller
public class SimpleController {
#Autowired
UserRepository userRepository;
#GetMapping("/mainPage")
public String viewMainPage(){
return "mainPage";
}
#GetMapping("/nuovo-utente")
public String viewInserisciUtente(Model model){
model.addAttribute("nuovoUtente", new Utente());
return "nuovo-utente";
}
#PostMapping("/nuovo-utente")
public String memorizzaUtente(#ModelAttribute Utente utente){
userRepository.save(utente);
return "output";
}
}
#Entity
public class Utente {
#Id
private int id;
private String citta=null;
private String genere=null;
private String data_nascita=null;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCitta() {
return citta;
}
public void setCitta(String citta) {
this.citta = citta;
}
public String getGenere() {
return genere;
}
public void setGenere(String genere) {
this.genere = genere;
}
public String getData_nascita() {
return data_nascita;
}
public void setData_nascita(String data_nascita) {
this.data_nascita = data_nascita;
}
}
Any help will be appreciated.
EDIT: I've added the entity class to help you understanding my problem. Hoping that this will help.
Thanks you all
If you look at CrudRepository documentation, then we don't have update method, but we only have save method, which is used to add or update existing records.
In your case, you might have updated an entity (except its Id field) and tried saving the entity. So, CrudRepository will update the existing value for given Id, since it is already present.
Try adding ID generation strategy to id field.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
I have a basic spring boot data rest api with posts that can have many comments. My problem is that I cant seem to find a way to post my comment directly to the sub resource uri such as http://localhost:8090/posts/1/comments.
The only way I've been able to do it was to to create the comment resource first at http://localhost:8090/comments and then post the uri of comment into http://localhost:8090/posts/1/comments.
It seems like a really bad idea as comments should never be able to exist on their own and only ever linked to a post.
Does anybody know how I can do this as one action, otherwise I'll have to manually deal with potential orphaned comments where the comment gets posted but never gets posted into http://localhost:8090/posts/1/comments for whatever reason.
My code is below.
Any help would be massively appreciated.
#Entity
public class Comment extends ResourceSupport {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonIgnore
private Long id;
private String comment;
#ManyToOne
private Post post;
#ManyToOne
private User sender;
protected Comment() {};
public void setId(Long id) {
this.id = id;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public User getSender() {
return sender;
}
public void setSender(User sender) {
this.sender = sender;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
#Entity
public class Post extends ResourceSupport {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private #JsonIgnore Long id;
private String text;
#OneToMany
private List<Comment> comments;
protected Post () {};
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
}
#RepositoryRestResource
public interface PostRepository extends PagingAndSortingRepository<Post, Long> {}
#RepositoryRestResource
public interface CommentRepository extends PagingAndSortingRepository<Comment, Long> {}
#SpringBootApplication
#EnableJpaRepositories("rest.api.repository")
#EnableWebMvc
#EnableTransactionManagement
#EnableAutoConfiguration
public class Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
the json im using to try to post the comment into the post is
{
"comment": "some text",
"sender": "http://localhost:8090/users/1"
}
It turned out that i needed to use mapped by i.e. #OneToMany(mappedBy = "post") on my comments list in my Post class.
Now i can post to http://localhost:8090/comments and then when i follow the http://localhost:8090/posts/1/comments link as before i now see the comments.
I tried the Spring Guide Accessing Data with MongoDB. What I can't figure out is how do I configure my code to not use the default server address and not use the default database. I have seen many ways to do it with XML but I am trying to stay with fully XML-less configurations.
Does anyone have an example that sets the server and database without XML and can be easily integrated into the sample they show in the Spring Guide?
Note: I did find how to set the collection (search for the phrase "Which collection will my documents be saved into " on this page.
Thank you!
p.s. same story with the Spring Guide for JPA -- how do you configure the db properties -- but that is another post :)
It would be something like this for a basic configuration :
#Configuration
#EnableMongoRepositories
public class MongoConfiguration extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "dataBaseName";
}
#Override
public Mongo mongo() throws Exception {
return new MongoClient("127.0.0.1", 27017);
}
#Override
protected String getMappingBasePackage() {
return "foo.bar.domain";
}
}
Example for a document :
#Document
public class Person {
#Id
private String id;
private String name;
public Person(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Example for a repository :
#Repository
public class PersonRepository {
#Autowired
MongoTemplate mongoTemplate;
public long countAllPersons() {
return mongoTemplate.count(null, Person.class);
}
}
I wanted to enable some auditing features, such as #CreatedDate. I am not using Spring xml configuration file, so I cannot add mongo:auditing to Spring configuration. I was wondering if there was an alternative way of enable auditing. The following code is the model for user. But whenever I create a user, the date is not stored in the document, so the auditing it's not working. Could someone give me some help?
#Document(collection = "user")
public class User {
#Id
private String id;
#Indexed(unique = true)
private String email;
private String name;
#CreatedDate
private Date date;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
Because you are not using configuration via XML, I believe you are using annotations. You own a class like this:
public class MongoConfig extends AbstractMongoConfiguration {...}
Thus, in addition to the annotations you should already have, add: #EnableMongoAuditing
Your configuration class will look like this now:
#Configuration
#EnableMongoRepositories(basePackages="...")
#EnableMongoAuditing
public class MongoConfig extends AbstractMongoConfiguration {...}
I hope this helps!
That's all you need. No subclasses or other stuff.
#Configuration
#EnableMongoAuditing
public class AnyConfig {}
You should write a configuration class in which you can connect to MongoDB database using mongoClient by passing db url. and add the anootaion of #EnableMongoAuditing on top of that class.