📜 ⬆️ ⬇️

Groovy integration into JEE application

  In one cart can not harness
 Horse and quivering doe
                         A.S.  Pushkin

Hello!

In this post I want to tell you how to integrate Groovy into an existing JEE application based on Maven. Thanks to Anton Shchastny schaan for permission to use the source code of his project as a starting point. Therefore, this topic can be considered a continuation of his article Learn to cook: Spring 3 MVC + Spring Security + Hibernate .

Let's start.

Project preparation.

I use Eclipse in the SpringSource Tool Suite build. We extort the project ContactManager . But do not rush to open it in the IDE. It will be even safer if you delete all the project files at all: .classpath .project and the .settings directory. For since the publication of the article, Anton's technology took a step forward, new versions of the STS came out (with a different project structure and a new version of the m2e plugin), so we first fix the pom-file, then based on the STS we will create a new project.
')
For simplicity, I removed from the pom.xml aspect dependencies and Spring Roo. I also replaced MySQL with a more familiar to me PostgreSQL (see jdbc.properties file). But this is all a saying, and here is a fairy tale: add dependency

<dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>1.8.6</version> </dependency> 


Actually, this is almost everything, Groovy is already integrated into our project. It remains only to deal with the joint compilation of Java and Groovy.

groovy-eclipse-compiler

About a year we used the plugin gmaven . We had our own “pitfalls” in working with him, it makes no sense to recall them already, because we switched to groovy-eclipse-compiler . Editing pom.xml

 <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> <encoding>UTF-8</encoding> <compilerId>groovy-eclipse-compiler</compilerId> </configuration> <dependencies> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-eclipse-compiler</artifactId> <version>2.6.0-01</version> </dependency> </dependencies> </plugin> 


Everything, with pom.xml finished, we start STS and we import the project into it. File -> Import -> Maven -> Existing Maven Projects. The Groovy Infected project looks completely normal.



STS does not swear, it's good, but for the purity of the experiment you need to collect all the maven. We carry out
 mvn clean package 

and we see what we are looking for in the log:

 [INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ contactmanager --- [INFO] Using Groovy-Eclipse compiler to compile both Java and Groovy files 


Go to Groovy

So, we practically said goodbye to java, we will continue to write on Groovy. There are already quite a few contacts, and we want to group these contacts by type: “family”, “work”, etc.

Let's start with POJO, I mean PO G O.

Create the src / main / groovy directory, add it to the BuildPath, create a package (in our example, com.acme.contactmanager.domain)

On the package, right-click -> New -> Groovy class

Let's call it ... let's say ... Half -act ContactType and write its source code:

 @Entity @Table(name = "CONTACT_TYPES", uniqueConstraints = [ @UniqueConstraint(columnNames = ["code"]), @UniqueConstraint(columnNames = ["name"]) ]) class ContactType { @Id @GeneratedValue Integer id @Basic @Column(unique = true, nullable = true) String code @Basic @Column(unique = true, nullable = true) String name @Basic @Column(nullable = true) Boolean defaulttype = false @OneToMany(fetch = FetchType.LAZY, cascade = [CascadeType.REFRESH, CascadeType.MERGE], mappedBy = "contacttype") List<Contact> contacts = null } 


Nothing supernatural, ordinary annotations, except that in arrays instead of curly brackets are square. No modifiers, setters , semicolons, all neatly-neat.

We inform Hiberneyta that we have a new entity.

 <hibernate-configuration> <session-factory> <mapping class="net.schastny.contactmanager.domain.Contact" /> <mapping class="com.acme.contactmanager.domain.ContactType" /> </session-factory> </hibernate-configuration> 


Add a new field to Contact.java, here you can’t do without getter setters

  @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.REFRESH, optional = false) private ContactType contacttype; public ContactType getContacttype() { return contacttype; } public void setContacttype(ContactType contacttype) { this.contacttype = contacttype; } 


We are going to deploy, and if the hibernatet has the option hibernate.hbm2ddl.auto = update, then we see the new table CONTACT_TYPES and the new field CONTACTS.contacttype_id in the database.

Note: If there are already contacts in the database, then the Hibernate will not be able to deliver the restriction, despite the presence of the annotation optinal = false. Filling the links with default values ​​and setting up a non-null restriction will be left to readers as homework.

Groovy dao

But it’s too early to stop there. The next step is groovy-dao. It, as in the case of java, should consist of an interface-implementation pair, otherwise Spring will not be happy. Repeat the steps of creating a package (this time - com.acme.contactmanager.dao) and creating the class ContactTypeDAO.groovy

 interface ContactTypeDAO { void addContactType(ContactType contactType) List<ContactType> listContactTypes() void removeContactType(Integer id) ContactType getDefault() } 


Everything is at 99% as in java, so go to the implementation. Not the pinnacle of programming skill, but enough for an example. The listContactTypes () method already contains the main charms for which we all started (see the comments in the code):

 @Repository class ContactTypeDAOImpl implements ContactTypeDAO { @Autowired private SessionFactory sessionFactory; private Session getCurrentSession() { sessionFactory.getCurrentSession() } @Override @Transactional void addContactType(ContactType contactType) { currentSession.save(contactType) } @Override @Transactional List<ContactType> listContactTypes() { //    get-    get    def result = currentSession.createQuery("from ContactType").list() // ,   ,   if(!result){ //  List<Map<String, Object>>?    ! def types = [ //     , //      [name:'', code:'family', defaulttype: false], [name:'', code:'job', defaulttype: false], [name:'', code:'stuff', defaulttype: true] ] //      types.each { type -> ContactType contactType = new ContactType( //   Groovy-    , //   Map code: type.code, name : type.name, defaulttype : type.defaulttype ) currentSession.save(contactType) //   <<     //  result     result << contactType } } //   return   result } @Override @Transactional void removeContactType(Integer id) { ContactType contactType = currentSession.get(ContactType.class, id) if (contactType) { currentSession.delete(contactType) } } @Override @Transactional ContactType getDefault() { currentSession.createCriteria(ContactType.class) .add(Restrictions.eq('defaulttype', true)) .uniqueResult() } } 


It remains to integrate the specific DAO into the Java service:
 public interface ContactService { //   -  ... public List<ContactType> listContactType(); } 


 @Service public class ContactServiceImpl implements ContactService { //   -  ... @Autowired private ContactTypeDAO contactTypeDAO; @Override @Transactional public List<ContactType> listContactType() { return contactTypeDAO.listContactTypes(); } } 


Add a call to the controller:
  @RequestMapping("/index") public String listContacts(Map<String, Object> map) { map.put("contact", new Contact()); map.put("contactList", contactService.listContact()); //     JSP map.put("contactTypeList", contactService.listContactType()); return "contact"; } 


We add localized messages to the files * .properties files and the drop-down list of types on JSP (see the project), we are going to deploy. Checking:



You can then use Groovy for tests, parse XML, etc. etc.

The source code of the project on GitHub .

Thank you for your attention, write to Groovy!

Links

Learning to cook: Spring 3 MVC + Spring Security + Hibernate
Groovy home
Groovy eclipse compiler
SpringSource Tool Suite
Programming Groovy: Dynamic Productivity for the Java Developer
Project Lombok, or declare war on a boilerplate

PS how to add tests to the project is written here . Including - tests for web-controllers.

Source: https://habr.com/ru/post/145158/


All Articles