A
A
Aleksey Pleshkov2016-11-01 00:48:03
Java
Aleksey Pleshkov, 2016-11-01 00:48:03

How to code in Kotlin correctly?

Good day. I am developing my first major project on Kotlin&Spring and I have a few questions related to code design.
1) How to avoid specifying in

activeUser!!.region = region
signs !! ? Like check for null I did.
var activeUser: User? = null
...
if (activeUser != null) {
                activeUser!!.region = region
                usersRepository.save(activeUser)
                return "success"
            }

2) How correct is it to check a variable for belonging to a class, and not != null ?
if (favoriteSelect is Favorite)
    usersModules.favoriteRepository.delete(favoriteSelect)

3) How to properly link two database entities? In one entity, add a list of several (@ManyToMany sort of). I need to place the ProductPrice list by product_id from the same entity in Product.productPrice . Product Essence
@Entity
@Table(name = "products")
data class Product(
        @Id @GeneratedValue(strategy = javax.persistence.GenerationType.AUTO)
        var id: Int = 0,
        var title: String = "",
        var img: String = "",
        var imgsSlider: String = "",
        var specialTag: String = "",
        var information: String = "",
        var composition: String = "",
        var uses: String = "",
        var dateUses: String = "",

        var date: Date = Date(),

        @OneToOne
        @JoinColumn(name = "user_id")
        var user: User? = null,

        @OneToOne
        @JoinColumn(name = "package_type")
        var packageType: PackageType? = null,

        @OneToOne
        @JoinColumn(name = "product_price")
        var productPrice: ProductPrice? = null,

        @OneToOne
        @JoinColumn(name = "product_type")
        var productType: ProductType? = null,

        @OneToOne
        @JoinColumn(name = "region_id")
        var region: Regions? = null,

        var tags: String = "",

        @OneToOne
        @JoinColumn(name = "catalog_id")
        var catalog: Catalog? = null,

        @OneToOne
        @JoinColumn(name = "stock_type")
        var stockType: StockType? = null)

In which there is a variable productPrice .
And the entity ProductPrice
@Entity
@Table(name = "products_price")
data class ProductPrice(
        @Id @GeneratedValue(strategy = javax.persistence.GenerationType.AUTO)
        var id: Int = 0,
        var productId: Int = 0,
        var packageCount: Int = 0,
        var price: Int = 0)

4) What is the correct way, in combat mode, to launch and configure a Spring application on the server? I run the Jar file from the terminal (added to autoload scripts on Ubuntu Server). But after a while the site stops working and gives an error
Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.TransactionException: JDBC begin transaction failed:

My build.gradle
group 'ru.test'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.0.3'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.6.RELEASE")
        classpath 'mysql:mysql-connector-java:5.1.34'
    }
}

apply plugin: 'kotlin'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'test'
    version =  '0.1.0'
}

springBoot {
    mainClass = 'ru.test.Application'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    // Kotlin
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

    // Spring
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("org.springframework.boot:spring-boot-starter-security")
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")

    // Others
    compile("org.hibernate:hibernate-validator")
    compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13'
    compile 'mysql:mysql-connector-java:5.1.31'
    compile 'commons-dbcp:commons-dbcp:1.4'

    // Tests
    testCompile("org.springframework:spring-test")
    testCompile("junit:junit")
    testCompile 'org.springframework.security:spring-security-test'
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}

jar {
    manifest {
        attributes 'Main-Class': 'ru.test.Application'
        attributes 'Class-Path': configurations.compile.collect { "lib/" + it.getName() }.join(' ')
    }

    into('lib') {
        from configurations.compile
    }
}

task copyDependencies(type: Copy) {
    into "$libsDir/lib"
    from configurations.compile
}

build.doLast {
    tasks.copyDependencies.execute()
}

And application.properties
# Settings site
server.port=8080

# Settings for database
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=yes&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.enable_lazy_load_no_trans = true

Thank you for your attention, I really hope for help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aleksey Igoshev, 2021-08-19
@Eisinheim

1) use of signs !! antipattern, well, if you explicitly bang the application with npe,

if (activeUser != null) {                            //тут уже выполнена проверка, 
                activeUser.region = region      //никаких !! знаков здесь быть не должно
                usersRepository.save(activeUser)
                return "success"
            }

use ?.let{ } run.. also.. apply..
activeUser?.also{ it.region = region }
activeUser?.apply{ age = 10}

2) you shouldn't do that, null is null on it and check
3) you don't quite understand the question you write "Add a list of several to one entity"
do you expect one object? and one-to-one relationship of tables
@OneToOne
        @JoinColumn(name = "product_price")
        var productPrice: ProductPrice? = null,

can expect @OneToMany sheet and table relation
@OneToMany (cascade = CascadeType.ALL)
        @JoinColumn(name = "product_price")
        var productPrice: List<ProductPrice>,

read more

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question