Translate

Mostrando las entradas con la etiqueta Hibernate. Mostrar todas las entradas
Mostrando las entradas con la etiqueta Hibernate. Mostrar todas las entradas

martes, 21 de junio de 2022

Como chequear si un registro esta siendo cacheado por Hibernate en una aplicación Spring boot.


Necesitaba ver si un registro estaba siendo cacheado por hibernate es decir JPA, en una aplicación spring boot. 

Hice lo que cualquiera hubiera hecho, puse show-sql en true, corrí un test que busca 2 veces el registro y me fije en el log que no hubiera 2 selects. Fácil pero poco científico, estaría bueno hacer un test que pruebe esto, y bueno hice esto : 


@RunWith(SpringJUnit4ClassRunner::class)

@SpringBootTest(classes = [Application::class])

class EjemploRepositoryTest {


    @Autowired

    lateinit var ejemploRepository: EjemploRepository


    @Autowired

    lateinit var entityManagerFactory: EntityManagerFactory


    @Test

    fun `find a Ejemplo from Empty cache`() {

        val ejemplo= getEjemplo()

        val cache = entityManagerFactory.cache

        Assert.assertFalse(cache.contains(Ejemplo::class.java, ejemplo.id))

    }


    @Test

    fun `find a Ejemplo from cache`() {

        val ejemplo= getEjemplo()

        saveAndFind(ejemplo)


        val cache = entityManagerFactory.cache


        Assert.assertTrue(cache.contains(Ejemplo::class.java, ejemplo.id))

    }


    private fun saveAndFind(ejemplo: Ejemplo): Ejemplo{

        ejemploRepository.save(ejemplo)

        return ejemploRepository.findById(ejemplo.id).get()

    }


    private fun getEjemplo(): Ejemplo{

        return  ... //Aca construimos un ejemplo 

    }


}

Y listo!!

domingo, 11 de julio de 2021

Web API en Groovy, Spring boot y H2

Vamos a hacer una web API con Groovy, Spring boot y H2 (como dice el título)

Primero vamos a bajar nuestro proyecto de https://start.spring.io/ bien no sé como indicar lo que hay que seleccionar. Pero creo que es bastante fácil, groovy, h2, etc. Voy a utilizar maven y dejo el link al final del repositorio y pueden ver el pom. 

Para comenzar vamos a hacer nuestras entidades : 

@Entity
@Table(name = 'Demos')
class Demo {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id

@Column
String unTexto

@Column
Boolean isUnCampoBool

@Column
LocalDate unaFecha

@OneToMany(cascade = CascadeType.ALL)
List<DemoItem> items = new ArrayList<>()

}

y

@Entity
@Table(name = 'DemoItems')
class DemoItem {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id

@Column
String unTexto
}

Luego el repositorio : 

@Repository
interface DemoRepository extends JpaRepository<Demo, Integer> {}

Ahora el servicio con su implementación: 

interface DemoService {

List<Demo> findAll()

Optional<Demo> findById(Integer todoId)

Demo insert(Demo demo)

Demo update(Demo demo)

Optional<Demo> delete(Integer id)

}
@Service
class DemoServiceImpl implements DemoService {

@Autowired
DemoRepository repository

@Override
List<Demo> findAll() {
return repository.findAll()
}

@Override
Optional<Demo> findById(Integer id) {
return repository.findById(id)
}

@Override
Demo insert(Demo demo) {
return repository.save(demo)
}

@Override
Demo update(Demo demo) {
return repository.save(demo)
}

@Override
Optional<Demo> delete(Integer id) {
Optional<Demo> demo = repository.findById(id)
if (demo.isPresent()) {
repository.delete(demo.get())
}
return demo
}
}

Y por ultimo el controller : 

@RestController
@RequestMapping('demo')
class DemoController {

@Autowired
DemoService service

@GetMapping
List<Demo> findAll(){
service.findAll()
}

@PostMapping
Demo save(@RequestBody Demo demo){
service.insert(demo)
}

@PutMapping
Demo update(@RequestBody Demo demo){
service.update(demo)
}

@DeleteMapping('/{id}')
delete(@PathVariable Integer id){
Optional<Demo> demo = service.delete(id)
if (!demo.isPresent()) {
throw new NotFoundException<Demo>(id)
}
return demo.get()
}

@GetMapping('/{id}')
Demo getById(@PathVariable Integer id){
Optional<Demo> demo = service.findById(id)
if (!demo.isPresent()) {
throw new NotFoundException<Demo>(id)
}
return demo.get()
}

}

Y el controller lanza una excepción cuando no encuntra elementos que es esta : 

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "not found")
class NotFoundException<T> extends RuntimeException {

private Long id

NotFoundException() {}

NotFoundException(Long id) {
this.id = id
}

@Override
String getMessage() {
return T + " not found"
}
}

Y listo!!!

Dejo el repositorio Github : https://github.com/emanuelpeg/GroovyWebAPI

jueves, 21 de mayo de 2020

Libros Gratuitos de Java Code Geek

Download IT Guides!

 

Vaadin Programming Cookbook

Vaadin is an open source web framework for rich Internet applications. In contrast to JavaScript libraries and browser-plugin based solutions, it features a server-side architecture,...

 
 

GWT Programming Cookbook

Google Web Toolkit, or GWT Web Toolkit, is an open source set of tools that allows web developers to create and maintain complex JavaScript front-end applications in Java. Other than a...

 
 

Amazon Elastic Beanstalk Tutorial

AWS Elastic Beanstalk is an orchestration service offered from Amazon Web Services for deploying infrastructure which orchestrates various AWS services, including EC2, S3, Simple...

 
 

Hibernate Tutorial

Hibernate ORM (Hibernate in short) is an object-relational mapping framework, facilitating the conversion of an object-oriented domain model to a traditional relational database....

 

jueves, 26 de septiembre de 2019

Libros Gratuitos desde Java Geek!!

Download IT Guides!

 
AWS Elastic Beanstalk is an orchestration service offered from Amazon Web Services for deploying infrastructure which orchestrates various AWS services, including EC2, S3, Simple...
 
 
Hibernate ORM (Hibernate in short) is an object-relational mapping framework, facilitating the conversion of an object-oriented domain model to a traditional relational database....
 
 
Eclipse is an integrated development environment (IDE) used in computer programming, and is the most widely used Java IDE. It contains a base workspace and an extensible plug-in system...
 
 
Learning the basics of Java is easy. But really delving into the language and studying its more advanced concepts and nuances is what will make you a great Java developer. The web is...
 

miércoles, 6 de febrero de 2019

Libros de Java Code Geeks

Download Dev Guides!

 
Bootstrap is a free and open-source collection of tools for creating websites and web applications. It contains HTML and CSS based design templates for typography, forms, buttons, navigation and other interface components, as well as optional JavaScript extensions. It aims to ease the development of dynamic websites and web applications. Bootstrap is a front end framework, that is, an interface for the user, unlike the server-side code which resides on the “back end” or server. Bootstrap is the most-starred project on GitHub, with over 88K stars and more than 37K forks. In this ebook, we provide a compilation of Bootstrap based examples that will help you kick-start your own web projects. 
 
 
Have you wondered what are the most common Javascript questions developers are asked in interviews? Well, in this minibook we’re going to go through some of the most anticipated questions (and their answers) to help you get going in job interviews and make a good impression with your knowledge.JavaScript developers are in high demand in the IT world. If this is the role that best expresses your knowledge and professionalism, you have a lot of opportunities to change the company you work for and increase your salary. But before you are hired by a company, you have to demonstrate your skills in order to pass the interview process.
 
 
Hibernate ORM (Hibernate in short) is an object-relational mapping framework, facilitating the conversion of an object-oriented domain model to a traditional relational database. Hibernate solves the object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions. Hibernate is one of the most popular Java frameworks out there. For this reason we have provided an abundance of tutorials here at Java Code Geeks, most of which can be found here. Now, we wanted to create a standalone, reference post to provide a framework on how to work with Hibernate and help you quickly kick-start your Hibernate applications. Enjoy!
 
 
Google Web Toolkit, or GWT Web Toolkit, is an open source set of tools that allows web developers to create and maintain complex JavaScript front-end applications in Java. Other than a few native libraries, everything is Java source that can be built on any supported platform with the included GWT Ant build files. It is licensed under the Apache License version 2.0. GWT emphasizes reusable approaches to common web development tasks, namely asynchronous remote procedure calls, history management, bookmarking, UI abstraction, internationalization, and cross-browser portability. In this ebook, we provide a compilation of GWT examples that will help you kick-start your own projects. 
 

sábado, 4 de agosto de 2018

5 Cursos de Spring Gratuitos


Si queremos aprender una tecnología nueva lo mejor es empezar por un libro o un curso y luego ir a tutoriales de internet. Saltar de tutorial en tutorial, nos da el conocimiento pero nos falta el orden. Con un curso o un libro aprendemos ordenadamente, como debe ser.

Por lo tanto dejo 5 cursos gratuitos para todos los que quieran empezar con Spring :

sábado, 7 de abril de 2018

Problema de database locking usando hibernate

Tuve un problema de database locking (loqueo en una búsqueda de castellanización) en la aplicación que estoy trabajando, el tema era que nadie debería escribir en la tabla que se loqueaba.

Lo primero que hice es ver el log de hibernate y pedirle que me muestre el sql, eso se logra cambiando el parámetro "show_sql". Analizando los sql, cuando se consultaba esta entidad hibernate hacia unos update y deletes que eran rarísimos, porque solo era una consulta. Es decir no debía hacer eso.

Luego de un analisis del codigo de consulta no encontre nada raro... Por lo tanto me puse a ver el mapeo y tampoco, nada raro...

Luego de caer en un pozo depresivo, vi la luz. Al parecer esta entidad estaba contenida por otra entidad, la cual en el método get ordenaba la lista. Parece ilógico, pero no lo es.

Cuando se hacia un get de esta lista, la aplicación ordenaba la lista y hibernate asumia que esta lista había cambiado, claro el no sabe que ya se había guardado ordenada. Por lo tanto cada vez que se hacia un get, hibernate removía la lista vieja y guardaba una nueva, sin importar si había cambios o no.

No se si esto se arreglo en futuras versiones de hibernate, pero como linea general traten siempre que usen hibernate que los métodos get no hagan nada (solo lo que deben hacer, retornar el valor)

Como lo solucione? muy fácil, hice un método get que no ordenaba, es decir el típico get y hice otro método getSorted que lo use en mi código. Y listo!

Espero que les sirva. 

viernes, 6 de abril de 2018

Libros gratuitos

Me llegaron ests libros de java geeks :

Get schooled by Java Code Geeks

Download Dev Guides!

 
Microsoft Azure is now more than seven years old. Like all seven-year-olds, Azure has been through some memorable teething troubles over the years, as well as some incredible growth and change. Microsoft still faces some significant challenges in increasing the adoption of its Azure platform. As Azure continues to evolve to meet the needs of modern app development processes and systems, developers will need to stay up to date with the latest changes in order to keep using the platform as efficiently as possible. In this eBook, we’ll look back at the history of Microsoft Azure and you’ll learn how to stay up to speed with Microsoft’s latest updates to Azure. You’ll also learn about the effect of the recent .NET Core release, as well as new considerations for app developers working with Azure and new ways they can use the platform to facilitate their app development processes. Finally, we’ll take a look at what’s new with Azure, exploring the innovations that could change the way developers work across platforms, both on-premises and in the cloud.
 
 
The primary intended audience for this document is any expert in professional services who needs to assure the health of SharePoint and systems connected to it. If you’re a systems architect, you can gain understanding of SharePoint components and how other applications can take advantage of SharePoint. If you’re an independent consultant, you’ll learn about the elements of comprehensive coverage and total visibility into operations with prebuilt monitoring configurations. Everything in this eBook is based on real-world examples and configurations where AppDynamics was deployed to monitor SharePoint. There’s no private or identifying information here, but it is not designed for the average SharePoint user. The level of detail can be overwhelming and not very useful for non-technical colleagues. This book can be used to help guide users through specific problems, but make sure that you work through those issues first and do not confuse the user with topics that take more specialized technical knowledge and experience.
 
 
IntelliJ IDEA is a Java integrated development environment (IDE) for developing computer software. It is developed by JetBrains, and is available as an Apache 2 Licensed community edition, and in a proprietary commercial edition. The IDE provides for integration with build/packaging tools like grunt, bower, gradle, and SBT. It supports version control systems like GIT, Mercurial, Perforce, and SVN. Databases like Microsoft SQL Server, ORACLE, PostgreSQL, and MySQL can be accessed directly from the IDE. IntelliJ supports plugins through which one can add additional functionality to the IDE. One can download and install plugins either from IntelliJ’s repository website or through IDE’s inbuilt plugin install feature. 
 
 
Hibernate ORM (Hibernate in short) is an object-relational mapping framework, facilitating the conversion of an object-oriented domain model to a traditional relational database. Hibernate solves the object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions. Hibernate is one of the most popular Java frameworks out there. For this reason we have provided an abundance of tutorials here at Java Code Geeks, most of which can be found here. Now, we wanted to create a standalone, reference post to provide a framework on how to work with Hibernate and help you quickly kick-start your Hibernate applications. Enjoy!
 

martes, 6 de febrero de 2018

20 libros que un desarrollador java debe leer en el 2018

En Dzone nos sugieren libros para leer en el 2018 y estoy bastante de acuerdo con la lista por lo tanto la comparto:

1. Java 8 in Action


best Java 8 books for programmers

2. Clean Architecture


best software architecture books for programmers

3. Grokking Algorithms

best Algorithm books for programmers

4. Building Microservices: Designing Fine-Grained Systems


best Microservices books for programmers

5. Soft Skills


best soft skill books for programmers

6. Database Design for Mere Mortals


best database design books for programmers

7. Making Java Groovy


best Groovy books for Java programmers

8. Groovy in Action, Second Edition


Image title

9. TCP/IP Illustrated


best book to learn TCP/IP protocol

10. UML Distilled


best book to learn UML

11. Hibernate Tips


Best book to learn Hibernate for experienced programmers

12. The Art of Agile Development


Best book to learn Agile

13. Essential Scrum


Best book to learn Scrum

14. Java Performance Companion


Best book to learn Java Performance Tuning

15. High-Performance Java Persistence


Best book to learn Java Persistence

16. Functional Programming in Scala


Best books to learn functional programming in Scala

17. Scala for the Impatient


Best books to learn  Scala

18. Head First JavaScript


Best books to learn JavaScript

19. SQL CookBook


Best books to learn SQL

20. The Complete Software Developer's Career Guide


Best books to take care of career development
Puff!! Tenemos mucho para leer!!

Dejo link: https://dzone.com/articles/20-books-java-programmers-should-read-in-2018